简体   繁体   English

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

[英]JQuery width and height not working on svg in firefox

I am trying to make SVG rectangle around SVG text. 我试图围绕SVG文本制作SVG矩形。 When i want to use .width() or .height() on SVG text, Chrome returns what I expect but Firefox does not. 当我想在SVG文本上使用.width().height()时,Chrome会返回我的预期,但Firefox不会。 Here is link to jsfiddle demo I made. 这是我制作的jsfiddle demo的链接。

$(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 HTML

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

css CSS

#svgArea{
    border: 1px solid black;
}

JQuery width() and height() ultimately rely on properties and methods of the elements themselves. JQuery width()height()最终依赖于元素本身的属性和方法。 Chrome implements an offsetWidth in the SVGTextElement prototype which allows jquery to return a width. Chrome在SVGTextElement原型中实现了offsetWidth ,允许jquery返回宽度。 But it's not a standard property and Firefox doesn't implement it. 但它不是标准属性,Firefox也没有实现它。

You can access width of svg text elements through the getBBox method. 您可以通过getBBox方法访问svg文本元素的宽度。 You can simply use it instead of jquery width. 您可以简单地使用它而不是jquery宽度。 Like this: 像这样:

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

See result: http://jsfiddle.net/nj413nbh/1/ 见结果: http//jsfiddle.net/nj413nbh/1/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM