对于Firefox & Safari中的svg: tspan元素,宽度似乎总是为零(或null)。
对于Firefox11和IE9中的SVG文本元素,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>发布于 2014-05-06 13:29:36
只要稍加修改代码,它就可以在以下方面工作:
看一看这个演示,看看它是否有效。
使用
$(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() (kudos 这里)。它的输出已经被整合到现场演示中。
https://stackoverflow.com/questions/23495756
复制相似问题