The width seems to be zero (or null) always for an svg:text tspan element in Firefox & Safari.
The jQuery functions width() and height() returns 0 for SVG tspan text elements in Firefox 11 and IE 9. In both Chrome 17 and 19 they work as expected. I have also tried usinf offsetWidth & getComputedTextLength() both returns 0 or null.
this is my query code:
$('svg #aitext-2-front-middle').find('tspan').each(function(i){
var currWidth = $(this).width();
console.log(currWidth);
});
This is the svg part:
<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>
A slight correction of your code makes it work in:
have a look at this demo to see it working.
use
$(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);
});
});
unfortunately the implicit browser switches appear to be necessary. in particular, the tspan
element does not have a getBBox
method in ie, whereas the text
element has.
EDIT :
an alternative might be to call getComputedTextLength()
(kudos go here ). Its output has been incorporated into the live demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.