Detect mousemove when over an iframe?

后端 未结 11 572
Happy的楠姐
Happy的楠姐 2020-11-29 05:47

I have an iframe that takes up the entire window (100% wide, 100% high), and I need the main window to be able to detect when the mouse has been moved.

Already tried

11条回答
  •  清酒与你
    2020-11-29 06:19

    MouseEvent.initMouseEvent() is now deprecated, so @Ozan's answer is a bit dated. As an alternative to what's provided in his answer, I'm now doing it like this:

    var bubbleIframeMouseMove = function( iframe ){
    
        iframe.contentWindow.addEventListener('mousemove', function( event ) {
            var boundingClientRect = iframe.getBoundingClientRect();
    
            var evt = new CustomEvent( 'mousemove', {bubbles: true, cancelable: false})
            evt.clientX = event.clientX + boundingClientRect.left;
            evt.clientY = event.clientY + boundingClientRect.top;
    
            iframe.dispatchEvent( evt );
    
        });
    
    };
    

    Where I'm setting clientX & clientY you'll want to pass any info from the content window's event to the event we'll be dispatching (i.e., if you need to pass something like screenX/screenY, do it there).

提交回复
热议问题