我有一个iframe,占据了整个窗口(100%宽,100%高),我需要主窗口能够检测到鼠标何时被移动。
我已经在iframe上尝试了一个onMouseMove
属性,但显然不起作用。我还尝试将iframe包装在div中,如下所示:
<div onmousemove="alert('justfortesting');"><iframe src="foo.bar"></iframe></div>
。。但它并没有起作用。有什么建议吗?
发布于 2012-08-08 20:58:11
如果你的目标不是Opera9或更低版本,IE9或更低版本,你可以使用css属性pointer-events: none
。
我发现忽略iframe是最好的方法。我在onMouseDown
事件中向iframe添加了具有此属性的类,并在onMouseUp
事件中将其删除。
对我来说太完美了。
发布于 2013-03-10 10:44:44
Iframes捕获鼠标事件,但如果满足跨域策略,则可以将事件传输到父范围。下面是操作步骤:
// 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的替代工具createEvent
、initMouseEvent
和dispatchEvent
。
发布于 2018-05-19 02:42:56
解决这个问题的另一种方法是在iframe(s)
上禁用鼠标移动事件,比如在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/
https://stackoverflow.com/questions/5645485
复制相似问题