处理重叠SVG图层中的鼠标事件 [英] Handling Mouse Events in Overlapping SVG Layers

查看:754
本文介绍了处理重叠SVG图层中的鼠标事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用d3.js构建地图可视化。我为美国各州和县绘制填充多边形。县的SVG图层位于状态层下。状态已填充,但fill-opacity设置为0;我想要捕获点击事件。

I am building a map visualization with d3.js. I am drawing filled polygons for both the US states and counties. The SVG layer for counties is under the layer for states. The states are filled, but fill-opacity is set to 0; the fill is required (I think) to catch click events.

我想捕获州级的点击事件,但我想捕获在县级的mouseover事件。

I want to catch click events at the state level, but I want to catch mouseover events at the county level.

但是,鼠标悬停事件由状态捕获,不会传递到县。

However, the mouseover event is captured by the states and not passed through to the counties.

推荐答案

这里有一个d3函数,它可以在一个层上传递事件

Here's a d3 function which does what you want.

通过暂时禁用顶层的指针事件,并手动触发下一层的鼠标事件,将事件传递给下层。

It passes events to lower layers by temporarily disabling pointer events on the top layer, and manually triggering the mouse event on the next layer.

function passThruEvents(g) {
    g   .on('mousemove.passThru', passThru)
        .on('mousedown.passThru', passThru)
    ;

    function passThru(d) {
        var e = d3.event;

        var prev = this.style.pointerEvents;
        this.style.pointerEvents = 'none';

        var el = document.elementFromPoint(d3.event.x, d3.event.y);

        var e2 = document.createEvent('MouseEvent');
        e2.initMouseEvent(e.type,e.bubbles,e.cancelable,e.view, e.detail,e.screenX,e.screenY,e.clientX,e.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget);

        el.dispatchEvent(e2);

        this.style.pointerEvents = prev;
    }
}

这篇关于处理重叠SVG图层中的鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆