Handling Mouse Events in Overlapping SVG Layers

前端 未结 2 2010
别跟我提以往
别跟我提以往 2021-02-15 01:04

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 sta

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-15 01:20

    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;
        }
    }
    

提交回复
热议问题