gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:29:40 30 4
gpt4 key购买 nike

我正在尝试制作一个特定的 <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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com