对于 Firefox 和 Safari 中的 svg:text tspan 元素,宽度似乎始终为零(或 null)。
对于 Firefox 11 和 IE 9 中的 SVG tspan 文本元素,jQuery 函数 width() 和 height() 返回 0。 在 Chrome 17 和 19 中,它们都按预期工作。 我也试过 usinf offsetWidth 和 getComputedTextLength() 都返回 0 或 null。
这是我的查询代码:
$('svg #aitext-2-front-middle').find('tspan').each(function(i){
var currWidth = $(this).width();
console.log(currWidth);
});
这是 svg 部分:
<text id="aitext-2-front-middle" transform="matrix(1 0 0 1 81.7744 155.248)">
<tspan x="66.287" y="57.6" font-family="'MyriadPro-Regular'" font-size="12">lightweight UIs using </tspan>
<tspan x="39.72" y="72" font-family="'MyriadPro-Regular'" font-size="12">Adobe Illustrator CS5 (or above) </tspan>
<tspan x="40.146" y="86.4" font-family="'MyriadPro-Regular'" font-size="12">along with some free resources. </tspan>
<tspan x="79.385" y="100.8" font-family="'MyriadPro-Regular'" font-size="12">Let’s get started.</tspan>
</text>
最佳答案
对您的代码稍作修改即可使其适用于:
- Chrome (34)
- 火狐 (28)
- ie(ie10标准模式和模仿ie9)
- Safari 5.1.7(Windows)
看看this demo看到它的工作。
使用
$(document).ready(function() {
$('svg #aitext-2-front-middle').find('tspan').each(function(i, e){
var currWidth;
currWidth = $(this).width();
if (!currWidth) {
currWidth = e.getBoundingClientRect().width;
if ((!currWidth) && (e.parentNode.getBBox)) {
currWidth = e.parentNode.getBBox().width;
}
}
console.log(currWidth);
});
});
不幸的是,隐式浏览器开关似乎是必要的。特别是,tspan
元素在 ie 中没有 getBBox
方法,而 text
元素有。
编辑:
替代方法可能是调用 getComputedTextLength()
(荣誉转到 here )。其输出已合并到现场演示中
关于javascript - 无法在 SVG 中获取 tspan 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23495756/