Javascript学习
延时提示框效果
简单说明:
定时器(
setInterval (函数,时间ms) 间隔型,一直
进行(一旦开启就会一直进行下去 )
setTimeout(函数, 时间ms)延时行,开启后只执行一次。
停止计时器:
clearInterval
clearTimeout
)
运用 js 的简单的事件效果
运用**开始计时器**和**结束计时器**
我们看看效果:
意思就是(需要满足的要求):
当鼠标移动到红区域上面的时候下面灰色的框会显示出来
当鼠标从红区域移动到灰区域上面时灰区域不消失
当鼠标移除灰色区域和红色区域的时候灰色区域会消失
下面看代码:
<!DOCTYPE html
>
<html
>
<head
>
<title
></title
>
<style type
="text/css">
#div1
{
height
: 30px
;
width
: 200px
;
background
-color
:red
;
}
#div2
{
height
: 20px
;
width
: 150px
;
background
: #ccc
;
margin
: 5px
;
display
: none
;
}
</style
>
</head
>
<body
>
<div id
="div1"></div
>
<div id
="div2"></div
>
<script type
="text/javascript">
window
.onload=function(){
var oDiv1
=document
.getElementById('div1');
var oDiv2
=document
.getElementById('div2');
var timer
=null;
function show(){
oDiv2
.style
.display
='block';
clearTimeout(timer
);
}
function hide(){
timer
=setTimeout(function(){
oDiv2
.style
.display
='none';
},300)
}
oDiv1
.onmouseover
=show
;
oDiv1
.onmouseout
=hide
;
oDiv2
.onmouseover
=show
;
oDiv2
.onmouseout
=hide
;
}
</script
>
</body
>
</html
>
说明:
一般做的时候他会出现好多种情况
就是你鼠标移除红区域还没等到移到灰区域的时候灰区域就消失了然后在一个问题就是当你鼠标在灰区域的时候然后再移出的时候,灰框不会消失。
解决这些问题就要用到计时器
解决第一个问题就可以开启一个定时器让鼠标移除红后块灰块会消失的函数中 开启一个定时器让它 300ms 后开启,这样就可以当你鼠标从红区域移动到灰区域的时候他不会消失。
解决第二个问题就是再鼠标移入的函数里写一个结束定时器,让上一个的定时器结束 ClearTimeout 。
这个问题解决了。
这样一个简单的延时提示框效果就做好了。
其中的 js 代码还可以简化
它可以这样写:
oDiv1.onmouseover=oDiv2.onmouseover=function(){}
//双等
简化后的代码如下:
<!DOCTYPE html
>
<html
>
<head
>
<title
></title
>
<style type
="text/css">
#div1
{
height
: 30px
;
width
: 200px
;
background
-color
:red
;
}
#div2
{
height
: 20px
;
width
: 150px
;
background
: #ccc
;
margin
: 5px
;
display
: none
;
}
</style
>
</head
>
<body
>
<div id
="div1"></div
>
<div id
="div2"></div
>
<script type
="text/javascript">
window
.onload=function(){
var oDiv1
=document
.getElementById('div1');
var oDiv2
=document
.getElementById('div2');
var timer
=null;
oDiv1
.onmouseover
=oDiv2
.onmouseover=function(){
oDiv2
.style
.display
='block';
clearTimeout(timer
);
}
oDiv1
.onmouseout
=oDiv2
.onmouseout=function(){
timer
=setTimeout(function(){
oDiv2
.style
.display
='none';
},300)
}
}
</script
>
</body
>
</html
>