在前端页面中经常要实现提示框功能,例如将鼠标放在qq头像上会出现提示框
如图:
当鼠标移开头像时提示框不会立马消失,当鼠标放到提示框上面提示框也不会消失。
使用js实现:
1.在body里面放两个div分别代表头像和提示框
<div id="ll">
<div id="div1">头像</div>
<div id="div2">提示框</div>
</div>
因为提示框是隐藏的所以要给提示框设置css display:none。
2.实现鼠标移动到头像时显示提示框:
var odiv1=document.getElementById('ll');
var odiv2=odiv1.getElementsByTagName('div');//获取头像和提示框
var timer=null;//定时器
odiv2[0].onmouseover=function () {
odiv2[1].style.display='block';
}
3.实现鼠标移除头像时提示框消失,用定时器实现延时消失,而不是立即消失,如果立即消失则无法将鼠标放到提示框上
odiv2[0].onmouseout=function () {
timer=setTimeout(function () {
odiv2[1].style.display='none';
},500);//过500ms提示框消失
}
4.但这时候鼠标移动到提示框上,提示框会消失,接下来实现鼠标移动到提示框上,提示框不会消失:
odiv2[1].onmouseover=function () {
clearTimeout(timer);//若不加此行500ms后提示框还是会消失,因此要停止定时器
odiv2[1].style.display='block';
}
5.设置鼠标移出提示框500ms后,提示框消失
odiv2[1].onmouseout=function () {
timer=setTimeout(function () {
odiv2[1].style.display='none';
},500);
}
6.现在有个问题,当鼠标从头像上移动到提示框上,然后再从提示框移动到头像上时,500ms后提示框会消失,因此当移入头像时要关掉定时器
7.总的代码如下:
<!DOCTYPE HTML>
<html>
<style type="text/css">
#div1{
height: 100px;
width: 100px;
background-color: yellow;
float: left;
}
#div2{
height: 100px;
width: 100px;
background-color: pink;
float: left;
display: none;
}
</style>
<body>
<div id="ll">
<div id="div1">头像</div>
<div id="div2">提示框</div>
</div>
</body>
<script>
/* document.write(document.compatMode);
var leftArr=[1,5,8,12,153,456];
var rightArr=[2,4,7,9,11,34];
function merge(leftArr,rightArr){
var n=[];
while(leftArr.length>0&&rightArr.length>0){
if(leftArr[0]<rightArr[0])
n.push(leftArr.shift());
else n.push(rightArr.shift());
}
return n.concat(leftArr).concat(rightArr);
}
var arr=merge(leftArr,rightArr);
alert(arr);*/
var odiv1=document.getElementById('ll');
var odiv2=odiv1.getElementsByTagName('div');//获取头像和提示框
var timer=null;//定时器
odiv2[0].onmouseover=function () {
clearTimeout(timer);
odiv2[1].style.display='block';
}
odiv2[0].onmouseout=function () {
timer=setTimeout(function () {
odiv2[1].style.display='none';
},500);
}
odiv2[1].onmouseover=function () {
clearTimeout(timer);
odiv2[1].style.display='block';
}
odiv2[1].onmouseout=function () {
timer=setTimeout(function () {
odiv2[1].style.display='none';
},500);
}
</script>
</html>