我创建了一个动画菜单,当用户光标位于屏幕右侧 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);
});
关于Javascript清除mousemove超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24803456/