[英]Asynchronous scroll event issue. Pure JS
I am running JavaScript in a Web Worker with use of AMP script.我正在使用 AMP 脚本在 Web Worker 中运行 JavaScript。 There are two event listeners - mouseenter and mouseout.
有两个事件侦听器 - mouseenter 和 mouseout。 Both events work as supposed to,
tooltipElem
appears on mouse enter and disappears on mouse out.这两个事件都按预期工作,
tooltipElem
在鼠标进入时出现并在鼠标离开时消失。 Here is my code:这是我的代码:
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;
}
});
When scroll event fired tooltipElem
is removed, but then I am unable to show it again on button
element click.当滚动事件触发
tooltipElem
被删除时,但我无法在button
元素单击时再次显示它。 To make mouseenter
work again I have to click at any other point on screen (feels like mouseout
fixes it).为了让
mouseenter
再次工作,我必须点击屏幕上的任何其他点(感觉像mouseout
修复了它)。
Doesn't work:不起作用:
document.addEventListener("scroll", async function(event) {
if (tooltipElem) {
tooltipElem.remove();
tooltipElem = null;
}
});
Tried to use interval, also doesn't work:尝试使用间隔,也不起作用:
var scrolling = false;
document.addEventListener("scroll", async function() {
scrolling = true;
});
setInterval( function() {
if (scrolling) {
scrolling = false;
if (tooltipElem) {
tooltipElem.remove();
tooltipElem = null;
}
}
}, 100 );
What can be wrong with my async scroll
?我的异步
scroll
什么问题? Maybe event is not finished or memory leaks?也许事件未完成或内存泄漏? No errors...
没有错误...
Here is a video, demonstrating scroll issue in the end (on second block).这是一个视频,最终演示了滚动问题(在第二个块上)。 https://streamable.com/y53749
https://streamable.com/y53749
Figured out that the problem is in mouseenter
event listener, so replaced it with click
on touch devices and mouseenter
on non-touch devices;发现问题出在
mouseenter
事件监听器上,于是用click
on touch devices and mouseenter
on non-touch devices; Didn't managed to detect device in amp-script
web worker using JS, so used Wordpress wp_is_mobile()
function;没有设法使用 JS 在
amp-script
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; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.