gpt4 book ai didi

javascript - JQuery 宽度和高度不适用于 firefox 中的 svg

转载 作者:太空狗 更新时间:2023-10-29 15:04:39 28 4
gpt4 key购买 nike

我正在尝试围绕 SVG 文本创建 SVG 矩形。当我想在 SVG 文本上使用 .width().height() 时,Chrome 会返回我期望的结果,但 Firefox 不会。这是 jsfiddle 的链接我制作的演示。

$(document).ready(function(){
var $rect = $(document.createElementNS('http://www.w3.org/2000/svg', 'rect'));
var x = 50;
var y = 50;
var fontSize = 10;
$rect.attr({
'x' : x,
'y' : y,
'stroke' : 'black',
'stroke-width' : 1,
'fill' : 'white'
});
$rect.appendTo($("#svgArea"));

var $svgText = $(document.createElementNS('http://www.w3.org/2000/svg', 'text'));
$svgText.attr({
'x': x,
'y': y,
'font-family' : 'verdana',
'font-weight': 'bold',
'font-size' : fontSize
});

var node = document.createTextNode("Lorem Ipsum");
$svgText.append(node);
$svgText.appendTo($("#svgArea"));

var textWidth = $svgText.width();
var textHeight = $svgText.height();

$rect.attr({
'x': x,
'y': y - textHeight + 3,
'width' : textWidth + 2,
'height': textHeight
});
});

html

    <svg height="200px" width="200px" id="svgArea">
</svg>

CSS

#svgArea{
border: 1px solid black;
}

最佳答案

JQuery width()height() 最终依赖于元素本身的属性和方法。 Chrome 在 SVGTextElement 原型(prototype) 中实现了一个offsetWidth,它允许 jquery 返回一个宽度。但它不是标准属性,Firefox 也没有实现它。

您可以通过 getBBox 方法访问 svg 文本元素的宽度。您可以简单地使用它而不是 jquery 宽度。像这样:

var textWidth = $svgText.get(0).getBBox().width;
var textHeight = $svgText.get(0).getBBox().height;

查看结果:http://jsfiddle.net/nj413nbh/1/

参见 BBox 规范:http://www.w3.org/TR/2011/REC-SVG11-20110816/types.html#__svg__SVGLocatable__getBBox

关于javascript - JQuery 宽度和高度不适用于 firefox 中的 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34711760/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com