<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>延迟提示符原理</title>
<style>
#div1 {
width: 200px;
height: 50px;
background: red;
}
#div2 {
width: 150px;
height: 80px;
background: gray;
margin: 10px;
display: none;
}
</style>
<script>
window.onload = function() {
var oDiv1 = document.getElementById('div1');
var oDiv2 = document.getElementById('div2');
var timer = null; //定义一个变量,它将是一个定时器,后面有赋值
oDiv1.onmouseover = function() {
oDiv2.style.display = 'block'; // 鼠标移入div1,div2出现
clearTimeout(timer); //清除timer,解决div2 300以后才会消失的问题
};
oDiv1.onmouseout = function() {
timer = setTimeout(function() {
oDiv2.style.display = 'none';
}, 200);
//setTimeout: 延时型定时器,只执行一次
// 鼠标移出div1,300毫秒以后div2消失
};
oDiv2.onmouseover = function() {
clearTimeout(timer); //清除timer,解决div2 300以后就会消失的问题
// 鼠标移入div2,希望它不消失。通过清除定时器的方法
};
oDiv2.onmouseout = function() {
timer = setTimeout(function() {
oDiv2.style.display = 'none';
}, 200);
};
// 在div1和div2之间移动时不会造成闪烁的问题
};
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>