getBoundingClientRect, incorrect height value for

2019-06-19 00:43发布

<body style="width:1000px;height:1000px;">
    <div id="d" style="display:inline-block;">
        <svg id="s" xmlns="http://www.w3.org/2000/svg" version="1.1" width="200px" height="200px">
          <rect width="200px" height="200px" style="fill:rgb(0,0,255);"/>
        </svg>
    </div>
</body>

var div = document.getElementById('d');
var rect = div.getBoundingClientRect();

alert(rect.width);  //200
alert(rect.height);  //205 (in safari), 204.5 in other browsers

var svg = document.getElementById('s');
var rect = svg.getBBox();

alert(rect.width);  //200
alert(rect.height);  //200

I'm trying to get the width and height of the parent div. For whatever reason, getBoudingClientRect is giving me an incorrect height value (205 or 204.5) The width is correct, but the height is off. Any ideas?

http://jsfiddle.net/jTvaF/5/

1条回答
叛逆
2楼-- · 2019-06-19 01:23

Give the svg the property of display:block; and it should start outputting correctly.

查看更多
登录 后发表回答