JavaScript mousemove事件侦听器无法按预期工作

时间:2018-12-26 01:46:33

标签: javascript html html5 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>元素内并且在元素内移动时显示。

我是否误解了Mozilla文档中为mousemove事件所描述的定义,该定义在上面的链接中找到?因为根据我的理解,这意味着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>

1 个答案:

答案 0 :(得分:1)

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

<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