我在使用AMP脚本的Web Worker中运行JavaScript。有两个事件监听器- mouseenter和mouseout。这两个事件都按预期工作,tooltipElem在鼠标输入时出现,在鼠标输出时消失。下面是我的代码:
const button = document.querySelector('.tooltip-trigger');
let tooltipElem;
button.addEventListener("mouseenter", async function(event) {
let target = event.target;
let tooltipHtml = target.getAttribute('data-tooltip-text');
if (!tooltipHtml) return;
tooltipElem = document.createElement('span');
document.body.appendChild(tooltipElem);
tooltipElem.innerHTML = tooltipHtml;
/* ... */
});
button.addEventListener("mouseout", async function(event) {
if (tooltipElem) {
tooltipElem.remove();
tooltipElem = null;
}
});当滚动事件触发的tooltipElem被移除时,然后我无法在button元素单击上再次显示它。要让mouseenter再次工作,我必须在屏幕上的任何其他位置单击(感觉像是mouseout修复了它)。
不起作用:
document.addEventListener("scroll", async function(event) {
if (tooltipElem) {
tooltipElem.remove();
tooltipElem = null;
}
});尝试使用间隔,也不起作用:
var scrolling = false;
document.addEventListener("scroll", async function() {
scrolling = true;
});
setInterval( function() {
if (scrolling) {
scrolling = false;
if (tooltipElem) {
tooltipElem.remove();
tooltipElem = null;
}
}
}, 100 );我的异步scroll会出什么问题?可能事件未完成或内存泄漏?无错误...
这是一个视频,演示了最后的滚动问题(在第二个块上)。https://streamable.com/y53749
发布于 2021-07-30 15:09:16
发现问题出在mouseenter事件监听器中,所以在触控设备上用click替换,在非触控设备上用mouseenter替换;在使用JS的web worker中检测不到设备,所以使用Wordpress wp_is_mobile()函数;
<?php if ( wp_is_mobile() ) : ?>
// Click (async)
button.addEventListener("click", addTooltip, false);
<?php else : ?>
// Mouseover (async)
button.addEventListener("mouseover", addTooltip, false);
<?php endif; ?>https://stackoverflow.com/questions/68574345
复制相似问题