最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - How do I set the style of SVG CSS attributes in Javascript? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to dynamically determine the length of an array of SVG paths and then insert this value into the HTML DOM style object for the attributes stroke-dasharray and stroke-dashoffset.

var horizontals = document.getElementsByClassName('hLine');
for (var i = 0; i < horizontals.length; i++ ) {
    var drawingComponent = horizontals[i],
        length = svgPiece.getTotalLength();

    horizontals[i].style.strokeDasharray = length;
    horizontals[i].style.strokeDashoffset = length;
}

In the example found here, all the .hLine paths (all the horizontal lines) should animate, but they do not. Is this because strokeDasharray and strokeDashoffset aren't supported?

I'm trying to dynamically determine the length of an array of SVG paths and then insert this value into the HTML DOM style object for the attributes stroke-dasharray and stroke-dashoffset.

var horizontals = document.getElementsByClassName('hLine');
for (var i = 0; i < horizontals.length; i++ ) {
    var drawingComponent = horizontals[i],
        length = svgPiece.getTotalLength();

    horizontals[i].style.strokeDasharray = length;
    horizontals[i].style.strokeDashoffset = length;
}

In the example found here, all the .hLine paths (all the horizontal lines) should animate, but they do not. Is this because strokeDasharray and strokeDashoffset aren't supported?

Share Improve this question asked May 18, 2014 at 22:15 OrunOrun 4,6033 gold badges30 silver badges45 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

For a start, there are some things wrong with that Javascript:

var horizontals = document.getElementsByClassName('hLine');

Your SVG doesn't have any elements with the class 'hLine'.

length = svgPiece.getTotalLength();

'svgPiece' is not defined anywhere.

Try something like this:

var horizontals = document.querySelectorAll('#horizontal path')

for (var i = 0; i < horizontals.length; i++ ) {
    var path = horizontals[i],
        length = path.getTotalLength();

    path.style.strokeDasharray = length;
    path.style.strokeDashoffset = length; 
}

Demo here - although there is still some work to do to get the animation working properly.

You can always also just fix the path length by setting pathLength (https://developer.mozilla/en-US/docs/Web/SVG/Attribute/pathLength) to a value (like 100 for easy percent-based modification).

发布评论

评论列表(0)

  1. 暂无评论