我有一个带有一堆路径的SVG(为简单起见,此处为rect
)
<rect id=1 x="0" y="100" width="100" height="100"/>
<rect id=2 x="120" y="100" width="100" height="100"/>
<rect id=3 x="240" y="100" width="100" height="100"/>
我的代码段定义了我的颜色:
var colors = ['red','yellow','green','blue','orange','purple','black','white'];
然后是将颜色随机化的代码段
var random_color1 = colors[Math.floor(Math.random() * colors.length)];
var random_color2 = colors[Math.floor(Math.random() * colors.length)];
var random_color3 = colors[Math.floor(Math.random() * colors.length)];
然后我将随机颜色应用于每个路径(每个路径都有唯一的ID)
document.getElementById('1').style.fill = random_color1;
document.getElementById('2').style.fill = random_color2;
document.getElementById('3').style.fill = random_color3;
事实是,本文档中有数百条路径。我需要将随机化应用于每条路径,我当前的过程剩下数百行代码。
我正在寻找一种方法;
random_color
函数,而不为每个路径创建一个新的,然后将其应用于该路径。我对javascript真的很陌生,我已经尝试了我所知道的一切,但无济于事。
- 不需要每个路径都有唯一的路径ID
您将需要某种与所有路径匹配的CSS选择器(仅此而已)。我提供了一个非常简单的方法,这是我目前可以做的所有事情,因为您没有进一步详细说明这些路径在HTML文档中的位置。
- 每次为一个路径调用random_color函数,而不为每个路径创建一个新的,然后将其应用于该路径。
一旦您解决了#1,这很容易-全部选择它们,遍历它们,并为每个颜色分配随机的颜色。
var colors = ['red','yellow','green','blue','orange','purple','black','white'];
var allPaths = document.querySelectorAll('svg rect');
allPaths.forEach(function (path) {
path.style.fill = colors[Math.floor(Math.random() * colors.length)];
});
<svg>
<rect x="0" y="100" width="100" height="100"/>
<rect x="120" y="100" width="100" height="100"/>
<rect x="240" y="100" width="100" height="100"/>
</svg>