选择编号在一定范围内的ID [英] Selecting IDs with numbers within a range
问题描述
我目前正在从事一项工作,要求我一次选择多个SVG元素.这些SVG元素中的每个元素都有一个id:人" +某个数字,范围从0到大约3000.在某些点上,我想一次为过渡动画选择一系列SVG元素.
I am currently working on something that requires me to select multiple SVG elements at a time. Each one of these SVG elements has an id: "person" + some number ranging from 0 to about 3000. During certain points, I would want to select a range of SVG elements at once for a transition animation.
我目前使用for循环来实现此功能,但是这似乎花费了太长时间,并导致过渡动画滞后.
I currently have this implemented with a for loop, however this seems to take too long and cause the transition animation to lag.
是否可以对ID在一定范围内的SVG项目执行selectAll?示例:person1-person3?
Is there a way to do a selectAll on SVG items that have the IDs within a range? Example: person1 - person3?
<div>
<rect x="5" y="52" width="5" height="5" id="person0"></rect>
<rect x="5" y="52" width="5" height="5" id="person1"></rect>
<rect x="5" y="52" width="5" height="5" id="person2"></rect>
<rect x="5" y="52" width="5" height="5" id="person3"></rect>
</div>
推荐答案
第一个逻辑选择是使用带有正则表达式的CSS属性选择器.但是,据我所知,CSS不支持选择器中的正则表达式.
The first logical choice would be using CSS attribute selectors with a regex. However, CSS does not support regex in selectors (as far as I know).
因此,另一种选择是使用 d3.range
创建ID范围,例如...
So, another choice is using d3.range
to create the range of IDs, like this...
d3.range(first ID value, last ID value + 1, 1).map(d=>"#person" + d).join(",")
...,您可以按照问题中的要求将其传递给 selectAll
:
... which you can pass to selectAll
, as you asked in the question:
是否可以对ID在一定范围内的SVG项目执行全选?
Is there a way to do a selectAll on SVG items that have the IDs within a range?
这是一个演示:
const start = 3;
const stop = 7;
d3.selectAll(d3.range(start, stop + 1, 1).map(d=>"#person" + d).join(","))
.style("fill", "wheat")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<rect x="5" y="10" width="10" height="50" id="person0"></rect>
<rect x="25" y="10" width="10" height="50" id="person1"></rect>
<rect x="45" y="10" width="10" height="50" id="person2"></rect>
<rect x="65" y="10" width="10" height="50" id="person3"></rect>
<rect x="85" y="10" width="10" height="50" id="person4"></rect>
<rect x="105" y="10" width="10" height="50" id="person5"></rect>
<rect x="125" y="10" width="10" height="50" id="person6"></rect>
<rect x="145" y="10" width="10" height="50" id="person7"></rect>
<rect x="165" y="10" width="10" height="50" id="person8"></rect>
<rect x="185" y="10" width="10" height="50" id="person9"></rect>
</svg>
这篇关于选择编号在一定范围内的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!