异步滚动事件问题。纯JS

Asynchronous scroll event issue. Pure JS

我 运行 JavaScript 在 Web Worker 中使用 AMP 脚本。有两个事件侦听器 - 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

发现问题出在 mouseenter 事件侦听器中,因此在触摸设备上将其替换为 click,在非触摸设备上将其替换为 mouseenter;未能使用 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; ?>