WEB開發人員有時候經常用到延時操作的用戶交互事件,比如聚美優品網站首頁的產品展示,當鼠標移入產品1秒鐘後,會顯示產品的詳情,而不希望用戶的鼠標指針剛剛移入元素就顯示詳情,對於不希望顯示詳情的用戶來說,達到了友好的交互作用,下面就要使用jQuery的計時器setTimeout,具體代碼如下:
HTML代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> < title >jQuery實現鼠標滑過延時顯示的效果-拓源網</ title > < script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></ script > < script type = "text/javascript" > $(function(){ $('.post').mouseover(function(){ hideTimer=setTimeout("$('.post > .demo').show();",1000);//鼠標滑過元素1秒鐘顯示子元素 }).mouseleave(function(){ clearTimeout(hideTimer);//清除計時器 hideTimer=setTimeout("$('.post > .demo').hide();",10);//鼠標移除元素區域子元素消失 }); }); </ script > < style type = "text/css" > <!-- * { margin:0; padding:0; } body { margin:0; padding:0; } div { font-size:26px; color:#fff; text-align:center; line-height:200px; } .box { width:980px; margin:0 auto; background:#eee; } .post { width:600px; height:200px; background:#36C; position:relative; } .demo { width:380px; height:200px; position:absolute; top:0; right:-380px; background:#F90; display:none; } --> </ style > </ head > < body > < div class = "box" > < div class = "post" >鼠標停留此處1秒鐘有驚喜!< div class = "demo" >恭喜看到一個溫暖的顏色。</ div ></ div > </ div > </ body > </ html > |
爲了不讓鼠標移入後立即移出該元素也同樣顯示子元素,需要使用clearTimeout(hideTimer)來清除計時器,這樣就能有效防止該問題發生。