从SVG中的shadowRoot元素向上遍历树



我正在准备监控火灾报警系统的可视化。Flor计划是用SVG制作的,探测器是图例中符号的克隆。我需要在鼠标悬停上显示当前活动/故障检测器的id。

鼠标悬停元素(克隆(:

<use
xmlns="http://www.w3.org/2000/svg"
x="0"
y="0"
xlink:href="#T0.000.0"
xmlns:xlink="http://www.w3.org/1999/xlink"
id="T0.2002.2"
width="100%"
height="100%"
transform="translate(214.99997,-507.73845)"
inkscape:label="#czujka"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
style="opacity: 1; fill: rgb(255, 255, 255); fill-opacity: 1; stroke: none; stroke-opacity: 1;"
/>

父元素(图例中(:

<g
xmlns="http://www.w3.org/2000/svg"
style="display:inline;fill-opacity:1;enable-background:new"
inkscape:label="#czujka"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
id="T0.000.0"
transform="matrix(0.97129703,0,0,0.88838831,-264.13104,95.785416)"
>
<rect
y="-65.32663"
x="547.59875"
height="13.507604"
width="12.354611"
id="rect11435"
style="fill-opacity:1;stroke:#000000;stroke-width:1.07652116;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:stroke markers fill"
/>
<path
inkscape:connector-curvature="0"
id="path11475" d="m 556.86474,-63.075369 c -15.44327,9.005071 9.26596,0 -6.17731,9.005071"
style="fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.07652116;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
sodipodi:nodetypes="cc"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
/>
</g>

鼠标光标正在选择矩形元素或路径元素。parentNode.id指向"T0.000.0",其parentNode为null。如何获取"T0.2002.2"元素的id?

从注释中移动的附加信息:

图例符号本身没有添加事件侦听器。探测器添加了事件侦听器:

function over(x) {
pop.innerHTML = x.originalTarget.parentNode.id;
var pageX = x.pageX;
var pageY = x.pageY + 25;
pop.style.left = pageX+"px";
pop.style.top = pageY+"px";
pop.style.display = 'block';
}
function out() {
pop.style.display = 'none';
}

您应该避免从影子根遍历到实例元素。如果将事件侦听器连接到<use>元素,事情会变得容易得多。例如,您可以给代表检测器的所有<use>元素一个class="detector",并编写如下内容:

var detectors = deocument.querySelectorAll('.detector');
function over(x) {
pop.innerHTML = x.currentTarget.id;
....
}
function out() {....}
detectors.forEach(function (el) {
el.addEventListener('mouseenter', over);
el.addEventListener('mouseleave', out);
});

最新更新