寫延時效果時很容易遇到一個惱人的問題:在 setTimeout 的函式裡使用 jQuery 的 $(this), selector 就是抓不到東西。這個問題背後其實有清楚的原因,解法也很乾淨。
嚴格來說,並不是「setTimeout 不支援 jQuery 選擇器」,而是 setTimeout 延遲執行時,回呼函式裡的 this 已經不再是原本那個 DOM 元素了。在非嚴格模式下,它會變成全域物件 window,因此 $(this) 包裝的是 window,自然找不到 siblings()。
$('.dl_select dt').hover(
function () {
clearTimeout(t3);
$(this).siblings('dd').css({ 'display': 'block', 'cursor': 'pointer' });
},
function () {
t2 = setTimeout(function () {
$(this).siblings('dd').css({ 'display': 'none' }); // 這裡的 this 已不是 dt
}, 300);
}
);
$('.dl_select dd').hover(
function () {
clearTimeout(t2);
$(this).css({ 'display': 'block', 'cursor': 'pointer' });
},
function () {
t3 = setTimeout(function () {
$(this).css({ 'display': 'none' });
}, 200);
}
);
$('.dl_select dt').hover(
function () {
clearTimeout(t3);
$(this).siblings('dd').css({ 'display': 'block', 'cursor': 'pointer' });
},
function () {
var $this = $(this).siblings('dd'); // 在 this 還正確時先存成變數
t2 = setTimeout(function () {
$this.css({ 'display': 'none' });
}, 300);
}
);
$('.dl_select dd').hover(
function () {
clearTimeout(t2);
$(this).css({ 'display': 'block', 'cursor': 'pointer' });
},
function () {
var $this = $(this);
t3 = setTimeout(function () {
$this.css({ 'display': 'none' });
}, 200);
}
);
除了用閉包保存變數,還有兩個常見做法:
Function.prototype.bind 綁定 this:setTimeout(function () { $(this).css(...) }.bind(this), 300)。setTimeout(() => { $(this).css(...) }, 300)。這是現在最推薦的寫法。順序上也要注意:這類「移入展開、移出收合」的效果,一定要搭配 clearTimeout,而且計時器變數最好宣告在全域或外層函式,否則每次觸發都會產生新的計時器,滑鼠快速移動時就會出現動畫打架。