我正在使用 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
答案 0 :(得分:0)
发现问题出在mouseenter
事件监听器上,所以在触摸设备上用click
替换它,在非触摸设备上用mouseenter
替换它;使用 JS 无法在 amp-script
网络工作者中检测到设备,因此使用了 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; ?>