jQuery实现鼠标滑过延时显示的效果

web前端 18745 11年前 (2013-09-23)

WEB开发人员有时候经常用到延时操作的用户交互事件,比如聚美优品网站首页的产品展示,当鼠标移入产品1秒钟后,会显示产品的详情,而不希望用户的鼠标指针刚刚移入元素就显示详情,对于不希望显示详情的用户来说,达到了友好的交互作用,下面就要使用jQuery的计时器setTimeout,具体代码如下:

HTML代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery实现鼠标滑过延时显示的效果-拓源网</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.4.2.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)来清除计时器,这样就能有效防止该问题发生。

分享给朋友: