Javascript清除mousemove超时

标签 javascript jquery html css timeout

我创建了一个动画菜单,当用户光标位于屏幕右侧 20 像素范围内时,该菜单会打开。如果用户光标在 2 秒内移出该区域,我想阻止菜单打开,但我正在为 Javascript 超时而苦苦挣扎。到目前为止,我的代码看起来像这样:

HTML

Javascript //定时器变量 变量计时器;

    function openToolbar()
    {               
        // Only execute for desktop
        $('.no-touch').on('mousemove',function(event) {

            // Toolbar and Window width
            var tableToolbar = $('.ac-table-toolbar'),
                winWidth = $(window).width();

            // If cursor enters right hand side of the screen start the timer
            // and execute after 2 seconds                  
            if(event.pageX > (winWidth - 20)) {

                // Timeout
                timer = setTimeout(function()
                {
                    // Add active class to toobar and css transition will animate it
                    // to open position
                    tableToolbar.addClass('active').removeClass('notActive');
                }, 2000);
            }

            // If mouse pointer leaves right hand side of the screen and
            // still has notActive class cancel the timeout to prevent
            // the toolbar from opening
            if(event.pageX < (winWidth - 20) && tableToolbar.hasClass('notActive'))
            {
                clearTimeout(timer);
            }

            // Toolbar has active class so we know its visible
            if(tableToolbar.hasClass('active') && event.pageX < (winWidth - 220))
            {
                // Clear timeout (if needed?)
                clearTimeout(timer);

                // Remove active class and css transition will return it to docked position
                tableToolbar.removeClass('active').addClass('notActive');
            }                   
        });
    }

动画由活跃的 notActive 类触发的 CSS 转换处理。

请任何人都可以指出我正确的方向。非常感谢。

最佳答案

这个任务太复杂了。大量的 mousemove 事件会降低您的页面速度。尝试使用另一种方法:

HTML:

<div id='rightActivateZone'></div>

CSS:

#rightActivateZone {
    background-color: red; // change to transparent for your purpose
    height: 100%;
    width: 20px;
    position: fixed;
    top: 0;
    right: 0;    
}

JS:

var timer;
$('#rightActivateZone').on('mouseenter', function() {
    timer = setTimeout(function() {
        alert('fire!'); // your code to show menu is here              
    }, 2000);
});
$('#rightActivateZone').on('mouseleave', function() {
    clearTimeout(timer);
});

JSFiddle demo

关于Javascript清除mousemove超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24803456/

相关文章:

javascript - i = i++ 和 i = i + 1 之间的区别

javascript - Tab容器刷新

javascript - 使用 Javascript 替换 HTML 中的 href 文本

javascript - 在html中制作可移动的菜单项

html - 背景图片不会在 github 页面上加载

html - 在 CSS 中将所有类转换为内联的最简单方法

javascript - 我想从 javascript 变量中设置样式属性

javascript - 根据对象名称过滤对象数组

javascript - 检测 jQuery 旋钮值

javascript - 两个具有相同id的元素,想要选择一个包含在特定div中的元素