简体   繁体   English

如何在 Javascript 中设置 SVG CSS 属性的样式?

[英]How do I set the style of SVG CSS attributes in Javascript?

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 .我正在尝试动态确定 SVG 路径数组的长度,然后将此值插入到 HTML DOM 样式对象的属性stroke-dasharraystroke-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.此处找到的示例中,所有.hLine路径(所有水平线)都应该有动画效果,但它们没有。 Is this because strokeDasharray and strokeDashoffset aren't supported?这是因为不支持strokeDasharraystrokeDashoffset吗?

For a start, there are some things wrong with that Javascript: 首先,Javascript存在一些问题:

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

Your SVG doesn't have any elements with the class 'hLine'. 您的SVG没有类“hLine”的任何元素。

length = svgPiece.getTotalLength();

'svgPiece' is not defined anywhere. 'svgPiece'没有在任何地方定义。

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. 在这里进行演示 - 尽管仍有一些工作要做,以使动画正常工作。

您也可以始终通过将 pathLength ( https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/pathLength ) 设置为一个值(如 100 以方便基于百分比的修改)来修复路径长度.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM