【发布时间】:2014-07-17 12:22:02
【问题描述】:
我创建了一个动画菜单,当用户光标位于屏幕右侧 20 像素以内时会打开该菜单。如果用户光标在 2 秒内移出该区域,我想阻止菜单打开,但我正在努力解决 Javascript 超时问题。到目前为止,我的代码如下所示:
HTML
Javascript // 定时器变量 var timer;
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 过渡处理。
请任何人指出我正确的方向。非常感谢。
【问题讨论】:
-
稍微跑题了,但是不需要每次鼠标移动都重新定义tableToolbar和winWidth,所以建议把
var tableToolbar = $('.ac-table-toolbar'), winWidth = $(window).width();移到mousemove事件回调之外。
标签: javascript jquery html css timeout