原理
- 采用鼠标划入划出事件
- 利用定时器延迟消失
- 清除定时器
代码实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>延时定时器模拟qq划过头像显示用户信息</title>
<style>
div{
float:left;
margin:10px;
}
#div1{
width: 50px;
height:50px;
background:red;
}
#div2{
width: 250px;
height: 180px;
background: #ccc;
display: none;
}
</style>
<script>
window.onload=function(){
var oDiv1=document.getElementById("div1");
var oDiv2=document.getElementById("div2");
var timer=null;
oDiv1.onmouseover=function(){
clearTimeout(timer);
oDiv2.style.display="block";
}
oDiv1.onmouseout=function(){
timer=setTimeout(function(){
oDiv2.style.display="none";
},500)
}
oDiv2.onmouseover=function(){
clearTimeout(timer);
}
oDiv2.onmouseout=function(){
timer=setTimeout(function(){
oDiv2.style.display="none";
},500)
}
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
把相同、相似代码进行合并
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>延时定时器模拟qq划过头像显示用户信息</title>
<style>
div{
float:left;
margin:10px;
}
#div1{
width: 50px;
height:50px;
background:red;
}
#div2{
width: 250px;
height: 180px;
background: #ccc;
display: none;
}
</style>
<script>
window.onload=function(){
var oDiv1=document.getElementById("div1");
var oDiv2=document.getElementById("div2");
var timer=null;
oDiv1.onmouseover=oDiv2.onmouseover=function(){
clearTimeout(timer);
oDiv2.style.display="block";
}
oDiv1.onmouseout=oDiv2.onmouseout=function(){
timer=setTimeout(function(){
oDiv2.style.display="none";
},500)
}
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。