Receive mousemove events from iframe, too

前端 未结 6 1175
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 08:17

I have a javascript app, whichs adds a mousemove listener to the document. Problem: When the mouse is moved over an iframe, the function is NOT called.

Is there a wa

6条回答
  •  臣服心动
    2020-12-03 08:49

    You should look through combining parent document event binding with document.getElementById('iFrameId').contentDocument event, witch allows you to get access to iFrame content elements.

    https://stackoverflow.com/a/38442439/2768917

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

提交回复
热议问题