gpt4 book ai didi

javascript - 如何获取svg元素类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:35:39 24 4
gpt4 key购买 nike

我有一个问题,我如何获得 svg 元素的类型,顺便说一句,我使用 d3.js

我有这样的东西

var selectedElement = svg.select("." + STYLE.selected);

if (selectedElement instanceof SVGCircleElement){
alert("here circle");
selectedElement.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
}
if (selectedElement instanceof SVGPathElement){
alert("here path");
appendMarkerm(selectedElement,false);

}

但似乎没有用,有人可以帮忙吗,谢谢!!


***finally, i made it work like this*** 

var selectedElement = svg.select("." + STYLE.selected);
if (selectedElement.node() instanceof SVGCircleElement){
selectedElement.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
}
if (selectedElement.node() instanceof SVGPathElement){
changeMarkerStyle(selectedElement,false);
}

cauz selection.node() 将返回选择的第一个元素

最佳答案

只需使用 tagName属性:

svg.select("." + STYLE.selected)
.call( function(){

switch( selectedElement.tagName.toLowerCase() ) {
case 'circle':
alert("here circle");
this.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
break;

case 'path':
alert("here path");
appendMarkerm( this, false );
break;
}

});

编辑

d3js' select()不返回元素本身,而是返回它的 d3js 包装器(非常类似于 jQuery,例如)。所以最简单的方法是使用 call()将函数应用于所有匹配项的方法(在只有 select() 的情况下,这只是一个)。

关于javascript - 如何获取svg元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18529521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com