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)来清除计时器,这样就能有效防止该问题发生。