在iframe上检测鼠标移动?

问题描述

| 我有一个iframe占用了整个窗口(宽度为100%,高度为100%),并且我需要主窗口来检测鼠标何时移动。 已经在iframe上尝试了“ 0”属性,但显然不起作用。还尝试将iframe包装在div中,如下所示:
<div onmousemove=\"alert(\'justfortesting\');\"><iframe src=\"foo.bar\"></iframe></div>
..却不起作用。有什么建议么?     

解决方法

如果您的目标不是Opera 9或更低版本以及IE 9或更低版本,则可以使用css属性
pointer-events: none
。 我发现这是忽略iframe的最佳方法。我在
onMouseDown
事件中将具有此属性的类添加到iframe,并在
onMouseUp
事件中删除。 对我来说很完美。     ,iframe会捕获鼠标事件,但是如果满足跨域策略,则可以将事件转移到父作用域。就是这样:
// This example assumes execution from the parent of the the iframe

function bubbleIframeMouseMove(iframe){
    // Save any previous onmousemove handler
    var existingOnMouseMove = iframe.contentWindow.onmousemove;

    // Attach a new onmousemove listener
    iframe.contentWindow.onmousemove = function(e){
        // Fire any existing onmousemove listener 
        if(existingOnMouseMove) existingOnMouseMove(e);

        // Create a new event for the this window
        var evt = document.createEvent(\"MouseEvents\");

        // We\'ll need this to offset the mouse move appropriately
        var boundingClientRect = iframe.getBoundingClientRect();

        // Initialize the event,copying exiting event values
        // for the most part
        evt.initMouseEvent( 
            \"mousemove\",true,// bubbles
            false,// not cancelable 
            window,e.detail,e.screenX,e.screenY,e.clientX + boundingClientRect.left,e.clientY + boundingClientRect.top,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,null // no related element
        );

        // Dispatch the mousemove event on the iframe element
        iframe.dispatchEvent(evt);
    };
}

// Get the iframe element we want to track mouse movements on
var myIframe = document.getElementById(\"myIframe\");

// Run it through the function to setup bubbling
bubbleIframeMouseMove(myIframe);
现在,您可以在iframe元素或其任何父元素上监听mousemove -事件将如您​​所愿地冒泡。 这与现代浏览器兼容。如果需要它与IE8及更低版本配合使用,则需要使用
createEvent
initMouseEvent
dispatchEvent
的IE专用替代品。     ,iframe中的页面是完整的文档。它将消耗所有事件,并且没有与其父文档的直接连接。 您将需要从子文档中的javascript捕获鼠标事件,然后以某种方式将其传递给父文档。     ,
MouseEvent.initMouseEvent()
现在已弃用,因此@Ozan的答案有些过时了。作为他回答中提供的替代方法,我现在正在这样做:
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 );

    });

};
在我将
clientX
clientY
设置为的情况下,您希望将内容窗口事件中的任何信息传递到我们将要调度的事件中(即,如果您需要传递
screenX
/
screenY
之类的信息,请执行在那里)。     ,在您的“父项”框架上,选择您的“子项” iframe,并检测您感兴趣的事件(以您的情况为例)
mousemove
这是在“父”框架中使用的代码示例
document.getElementById(\'yourIFrameHere\').contentDocument.addEventListener(\'mousemove\',function (event) {
                console.log(,event.pageX,event.pageY,event.target.id);
            }.bind(this));
    ,解决这个问题的另一种方法是对ѭ17is禁用鼠标移动事件,例如对
mouse down
进行操作:
$(\'iframe\').css(\'pointer-events\',\'none\');
然后,在
mouse up
iframe(s)
上重新启用鼠标移动事件:
$(\'iframe\').css(\'pointer-events\',\'auto\');
我尝试了上面的其他一些方法,但它们确实有效,但这似乎是最简单的方法。 感谢:https://www.gyrocode.com/articles/how-to-detect-mousemove-event-over-iframe-element/     ,我曾经遇到过类似的问题,我想在iFrame上拖动div \。问题是,如果鼠标指针移到div之外,移到iFrame上,则会丢失mousemove事件,并且div停止拖动。如果这是您想要做的事情(而不是仅检测到用户在iFrame上挥动鼠标),我在另一个问题线程中找到了一个建议,当我尝试它时似乎很好。 在包含和要拖动的内容的页面中,还应包含以下内容:
<div class=\"dragSurface\" id=\"dragSurface\">
<!-- to capture mouse-moves over the iframe-->
</div>
将其初始样式设置为如下所示:
.dragSurface
{
  background-image: url(\'../Images/AlmostTransparent.png\');
  position: absolute;
  z-index: 98;
  width: 100%;
  visibility: hidden;
}
\ '98 \'的z-index是因为我将要拖动的div \设置为z-index:99,而iFrame设置为z-index:0。 当您在要拖动的对象(不是dragSurface div)中检测到mousedown时,请在事件处理程序中调用以下函数:
function activateDragSurface ( surfaceId )
{
  var surface = document.getElementById( surfaceId );
  if ( surface == null ) return;

  if ( typeof window.innerWidth != \'undefined\' )
  { viewportheight = window.innerHeight; } 
  else
  { viewportheight = document.documentElement.clientHeight; }

  if ( ( viewportheight > document.body.parentNode.scrollHeight ) && ( viewportheight > document.body.parentNode.clientHeight ) )
  { surface_height = viewportheight; }
  else
  {
    if ( document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight )
    { surface_height = document.body.parentNode.clientHeight; }
    else
    { surface_height = document.body.parentNode.scrollHeight; }
  }

  var surface = document.getElementById( surfaceId );
  surface.style.height = surface_height + \'px\';
  surface.style.visibility = \"visible\";
}
注意:我大部分都是从我在互联网上找到的其他人的密码抄来的!大部分的逻辑都可以用来设置dragSurface的大小来填充框架。 因此,例如,我的onmousedown处理程序如下所示:
function dragBegin(elt)
{
  if ( document.body.onmousemove == null )
  {
    dragOffX = ( event.pageX - elt.offsetLeft );
    dragOffY = ( event.pageY - elt.offsetTop );
    document.body.onmousemove = function () { dragTrack( elt ) };
    activateDragSurface( \"dragSurface\" ); // capture mousemoves over the iframe.
  }
}
当拖动停止时,您的onmouseup处理程序应包含对此代码的调用:
function deactivateDragSurface( surfaceId )
{
  var surface = document.getElementById( surfaceId );
  if ( surface != null ) surface.style.visibility = \"hidden\";
}
最后,创建背景图像(在上面的示例中为AlmostTransparent.png),并使其除完全透明以外的所有内容。我用alpha = 2制作了8x8图像。 到目前为止,我仅在Chrome中对此进行了测试。我还需要使其在IE中正常工作,并且将尝试使用在此发现的内容来更新此答案!     ,
<script>
// dispatch events to the iframe from its container
$(\"body\").on(\'click mouseup mousedown touchend touchstart touchmove mousewheel\',function(e) {
    var doc = $(\"#targetFrame\")[0].contentWindow.document,ev = doc.createEvent(\'Event\');
    ev.initEvent(e.originalEvent.type,false);
    for (var key in e.originalEvent) {
        // we dont wanna clone target and we are not able to access \"private members\" of the cloned event.
        if (key[0] == key[0].toLowerCase() && $.inArray(key,[\'__proto__\',\'srcElement\',\'target\',\'toElement\']) == -1) {
            ev[key] = e.originalEvent[key];
        }
    }
    doc.dispatchEvent(ev);
});
</script>
<body>
<iframe id=\"targetFrame\" src=\"eventlistener.html\"></iframe>
</body>
    ,对于类似的问题,我发现了一个相对简单的解决方案,当时我想调整iframe的大小,并在其旁边放置一个div。一旦鼠标移过iframe,jquery就会停止检测鼠标。 为了解决这个问题,除了div的z索引(设置为0)和iframe(设置为1)外,我都将div与iframe一起放置在相同的区域中,并且样式相同。这样就可以在不调整大小的情况下正常使用iframe。
<div id=\"frameOverlay\"></div>  
<iframe></iframe>
调整大小时,div z-index设置为2,然后再返回0。这意味着iframe仍然可见,但是覆盖层阻止了它,从而可以检测到鼠标。     ,该代码似乎可以正常运行,尽管效果不是很好:
<div id=\"test\" onmousemove=\"alert(\'test\');\">
    <iframe style=\"width:200px; height:200px; border:1px solid black;\">
        <p>test</p>
    </iframe>
</div>  
该事件确实会在每次鼠标移动时触发,但仅限于其中一些触发。我不知道该事件内部是否存在某种内部事件缓冲区。     ,您可以在开始拖动时(onmousedown事件)在iframe上添加覆盖,而在结束拖动时(mouserup事件)则将其删除。 jQuery UI.layout插件使用此方法来解决此问题。