首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步滚动事件问题。纯JS

问异步滚动事件问题。纯JS
EN

Stack Overflow用户
提问于 2021-07-29 18:33:33
回答 1查看 112关注 0票数 0

我在使用AMP脚本的Web Worker中运行JavaScript。有两个事件监听器- mouseenter和mouseout。这两个事件都按预期工作,tooltipElem在鼠标输入时出现,在鼠标输出时消失。下面是我的代码:

代码语言:javascript
复制
    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修复了它)。

不起作用:

代码语言:javascript
复制
    document.addEventListener("scroll", async function(event) {
    
        if (tooltipElem) {
            tooltipElem.remove();
            tooltipElem = null;
        }   
        
    });

尝试使用间隔,也不起作用:

代码语言:javascript
复制
    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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-30 15:09:16

发现问题出在mouseenter事件监听器中,所以在触控设备上用click替换,在非触控设备上用mouseenter替换;在使用JS的web worker中检测不到设备,所以使用Wordpress wp_is_mobile()函数;

代码语言:javascript
复制
    <?php if ( wp_is_mobile() ) : ?>
    
    // Click (async)
    button.addEventListener("click", addTooltip, false);
    
    <?php else : ?>

    // Mouseover (async)
    button.addEventListener("mouseover", addTooltip, false);
    
    <?php endif; ?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68574345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档