在iframe上检测鼠标移动?

如何解决在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插件使用此方法来解决此问题。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-