从SVG中的shadowRoot元素遍历树

时间:2018-11-08 15:47:59

标签: javascript dom svg traversal

我正在准备可视化监视火警系统。 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';
}

1 个答案:

答案 0 :(得分:0)

应避免从影子根遍历到实例元素。如果将事件侦听器附加到<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);
 });