簡體   English   中英

JQuery的寬度和高度不適用於firefox中的svg

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

我試圖圍繞SVG文本制作SVG矩形。 當我想在SVG文本上使用.width().height()時,Chrome會返回我的預期,但Firefox不會。 這是我制作的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

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

CSS

#svgArea{
    border: 1px solid black;
}

JQuery width()height()最終依賴於元素本身的屬性和方法。 Chrome在SVGTextElement原型中實現了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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM