参考这个例子:
$(document).ready(function() {
var body = $('body'),
text = $('#text');
body.append('<br /><strong>jQuery</strong>');
body.append('<p>Width: ' + text.width() + '</p>');
body.append('<p>Height: ' + text.height() + '</p>');
body.append('<br /><strong>getBoundingClientRect</strong>');
body.append('<p>Width: ' + text[0].getBoundingClientRect().width + '</p>');
body.append('<p>Height: ' + text[0].getBoundingClientRect().height + '</p>');
});
svg {
border: 1px solid #3d3d3d;
}
<p>
This example works as expected in Chrome 19, but not
in Firefox 11 and Internet Explorer 9.
</p>
<br /><br />
<svg version="1.1" width="600" height="200">
<text x="100" y="100" class="mediumText" id="text">jQuery rocks!</text>
</svg>
结果是包含文本的框的高度(用鼠标选择文本可以看到的高度),该高度高于文本的实际高度。
有没有办法用 jQuery 或普通 JS 获取真实高度?
在我尝试过的示例中
text.height()
和
text[0].getBoundingClientRect().height
不幸的是,它显示的是 19px 而不是 14px。
为您的文本元素获取计算出的
font-size
:
parseInt(window.getComputedStyle(text[0]).fontSize, 10);
font-size
表示字体的全角方形的大小。 应该注意的是,虽然大多数字形将保留在全角形的边界内,但有些“可能”会超出这些边界。 不过,这通常不会发生在垂直维度上。
尝试一下:http://jsfiddle.net/uzgJX/1/。 提示:屏幕截图并复制到您最喜欢的图像编辑器中,然后选择与文本高度完全一致的像素,并与小提琴中给出的值进行比较。