svg.js - 不知道元素类型的 CSS 选择器
问题描述
我正在尝试渲染游戏板。我定义了一个通用的“片断”组,它可以包含许多不同的元素。没有什么能阻止用户制作他们想要的复杂游戏。但我需要知道的是哪些元素需要用当前播放器颜色填充。我希望使用select()
和 CSS 选择器来做到这一点。
不过,问题在于 SVG.js 似乎在类名前面加上了元素的类型,但渲染代码不需要这些信息。
这是代码:
var canvas = SVG('canvas')
// Create a new group in the <defs> tag that will contain the piece
const group = canvas.defs().group().id("piece");
// Add various elements to the piece.
group.circle(100)
// Only *this* element should be filled with a colour
.addClass("playerfill")
.fill("#fff")
.stroke({width: 2, color: "#000"});
group.circle(5).center(50,50).fill("black");
var use = SVG.get("piece");
// I have to prepend `circle.` to make this work!
var set = use.select("circle.playerfill").fill("red");
canvas.use(use);
这是小提琴:https ://jsfiddle.net/Perlkonig/so12hev3/ 。
如果不是按 ID(组可能包含多个需要填充的元素)或 CSS 类(我显然需要知道用户选择的元素类型),我如何标记组中的元素以供以后选择和操作?
更新:
这是答案。谢谢,邓肯!
解决方案
您应该能够添加任何您喜欢的属性,只要它以 . 开头data-
,例如data-condition="alive"
. 然后,您可以使用 CSS 选择器进行选择[data-condition="alive"]
。
您可以使用属性进行更复杂的选择,请参阅https://www.w3schools.com/css/css_attribute_selectors.asp