首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在iframe上检测鼠标移动?

在iframe上检测鼠标移动?
EN

Stack Overflow用户
提问于 2011-04-13 14:54:50
回答 11查看 48.4K关注 0票数 35

我有一个iframe,占据了整个窗口(100%宽,100%高),我需要主窗口能够检测到鼠标何时被移动。

我已经在iframe上尝试了一个onMouseMove属性,但显然不起作用。我还尝试将iframe包装在div中,如下所示:

代码语言:javascript
复制
<div onmousemove="alert('justfortesting');"><iframe src="foo.bar"></iframe></div>

。。但它并没有起作用。有什么建议吗?

EN

回答 11

Stack Overflow用户

发布于 2012-08-08 20:58:11

如果你的目标不是Opera9或更低版本,IE9或更低版本,你可以使用css属性pointer-events: none

我发现忽略iframe是最好的方法。我在onMouseDown事件中向iframe添加了具有此属性的类,并在onMouseUp事件中将其删除。

对我来说太完美了。

票数 33
EN

Stack Overflow用户

发布于 2013-03-10 10:44:44

Iframes捕获鼠标事件,但如果满足跨域策略,则可以将事件传输到父范围。下面是操作步骤:

代码语言:javascript
复制
// 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及更低版本中使用它,则需要使用特定于IE的替代工具createEventinitMouseEventdispatchEvent

票数 27
EN

Stack Overflow用户

发布于 2018-05-19 02:42:56

解决这个问题的另一种方法是在iframe(s)上禁用鼠标移动事件,比如在mouse down上禁用鼠标移动事件

代码语言:javascript
复制
$('iframe').css('pointer-events', 'none');

然后,在mouse up上的iframe(s)上重新启用鼠标移动事件

代码语言:javascript
复制
$('iframe').css('pointer-events', 'auto');

我尝试了上面的一些其他方法,它们都有效,但这似乎是最简单的方法。

致谢:https://www.gyrocode.com/articles/how-to-detect-mousemove-event-over-iframe-element/

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5645485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档