Javascript mousemove 事件监听器未按预期工作

标签 javascript html iframe dom-events

我正在尝试制作一个特定的 <p>仅当我的鼠标位于 <iframe> 范围内时,元素才保持可见元素并在 <iframe> 内移动元素。如果鼠标在 <iframe> 之外元素或在 <iframe> 内静止元素,那么它应该隐藏 <p>元素。

我正在使用 mousemove事件监听器,查看 https://developer.mozilla.org/en-US/docs/Web/Events/mousemove 后,它定义了 mousemove事件为“当指针设备(通常是鼠标)在元素上方移动时,会触发 mousemove 事件。”

但是,如果您在 HTML 片段上测试代码,我的情况似乎并非如此,因为一旦我的鼠标在 <iframe> 内移动,它确实使<p>元素元素,但是在一段时间后,超时触发并隐藏它,它仍然会消失。在 iframe 元素内移动鼠标,似乎不会触发 mousemove再次事件,直到将鼠标移到 iframe 之外窗口,然后再次将其移回。

还有mousemove当我从 <iframe> 外部移动鼠标时,事件并不总是被触发元素到元素内部。

有人可以向我解释一下为什么 mousemove当鼠标在 <iframe> 范围内移动时,事件不会再次触发元素并告诉我如何实现我的 <p>元素仅在鼠标位于 <iframe> 范围内时出现元素并在元素内部移动。

我是否误解了mousemove描述的定义mozilla 文档中的事件,可以在上面的链接中找到吗?因为根据我的理解,这意味着 mousemove当鼠标在元素内移动时将触发事件。

非常感谢,圣诞快乐。

function showP() {
  document.getElementById('p').classList.remove('hide');
}

function hideP() {
  document.getElementById('p').classList.add('hide');
}

var timer;

document.getElementsByClassName('iframe')[0].addEventListener('mousemove', function() {
  console.log('Entered iframe');
  clearTimeout(timer);
  showP();
  timer = setTimeout(hideP, 3000);
});
.hide {
  display: none;
}
<iframe class="iframe" src="https://test.com/" width="100px" height="100px">

</iframe>

<p id="p" class="hide">
  Showing P Tag
</p>

最佳答案

Iframe 可能很棘手。您可以尝试将 iframe 包装在 div 中,然后在 JS 中定位该 div:

<div class="iframe" width="100px" height="100px">
   <iframe src="https://test.com/" width="100px" height="100px">
   </iframe>
</div>

我很确定这样您也可以使用 onmouseover 和 onmouseout 或任何其他事件。您可能需要添加 CSS:

iframe {
pointer-events: none;
}

查看工作代码笔:https://codepen.io/geochanto/pen/wRqvqo

关于Javascript mousemove 事件监听器未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53926741/

相关文章:

javascript - 从 testcomplete 连接到本地数据库

javascript - 在 ES2015 中使用枚举

javascript - 如何在 Ejabberd 中启用基于角色的用户聊天

iframe - iframe 页面可以告诉它们何时被 iframe 吗?

javascript - 如何使用 IONIC 访问 iPhone 系统时钟

javascript - 如何让我的 matchMedia 在我的调整大小事件监听器中工作?

html - 如何为占位符中的最后一个字符设置颜色

html - 在 HTML 和 CSS 中用作按钮的居中文本

javascript - 如何调整 JavaScript 小部件的大小?

iframe - 在 iframe 中查看我的网站是否会损害我的 SEO?