在qq主页面板上的最上方有自己的用户名,往用户名上移动会出现一个大框,往大框中移动,大框不会消失,如果离开大框或者姓名,大框就会消失,这一功能用到display:none的效果还有就是计时器的延时功能,用到onmoseover;
onmouseover 属性在鼠标指针移动到元素上时触发。
注释:onmouseover 属性不适用以下元 素:<base>、<bdo>、<br>、<head>、<html>、<iframe>、<meta>、<param>、<script>、<style> 或 <title>。
onmoseover的相反是onmouseout;
且看如下代码:
HTML代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>javascript二级联动</title> <style type="text/css"> #block1{ 40px; height: 40px; background: red; float: left; } #block2{ 240px; height: 240px; background: gray; float: left; margin-left: 5px; } </style> </head> <body> <div id = "block1"></div> <div id = "block2"></div> </body> </html>
javascript代码如下:
var block1 = document.getElementById("block1"); var block2 = document.getElementById("block2"); block1.onmouseover = function(){ block2.style.display = 'block'; }
这一步实现的是将鼠标移到block1的时候block2出现;但是鼠标离开block1,block2仍然出现,我们需要将block2消失,则需要用到onmoseout来操作,如下:
block1.onmouseout = function(){ block2.style.display = 'none'; }
但是,这个效果还是有欠缺,因为从block1移动到block2的时候无法选中block2,而是很快的消失了,那么,我们需要一个延时来让block2慢点消失,给他一个setTimeout,并且500毫秒,因为setTimeout会有一个返回值,所以在之前设置一个var timer = null;一开始timer不知道要赋值什么,所以为null,再在下面的程序中将值付给timer,如下:
block1.onmouseout = function(){ timer = setTimeout("block2.style.display = 'none'",1000); }
移到block2时需要block2一直显示,并且,之前block1的延时取消none这个延时的动作,所以如下代码:
block2.onmouseover = function(){ clearTimeout(timer); block2.style.display = 'block'; }
那么block2移除鼠标时会怎么样呢?我们希望移除block2会消失,并且,移到block1的时候依然为显示,所以这边也需要一个延时,然后在block鼠标以上去的时候清除定时器的延时,这样block2移到block1上时不会出现消失了。如下代码
block2.onmouseout = function(){ time = setTimeout(" block2.style.display = 'none'",1000); }
javascript总的代码如下:
var block1 = document.getElementById("block1"); var block2 = document.getElementById("block2"); var timer = null; block1.onmouseover = function(){ block2.style.display = 'block'; clearTimeout(time); } block1.onmouseout = function(){ timer = setTimeout("block2.style.display = 'none'",1000); } block2.onmouseover = function(){ clearTimeout(timer); block2.style.display = 'block'; } block2.onmouseout = function(){ timer = setTimeout(" block2.style.display = 'none'",1000); }
block1.onmuseout与 block1.onmouseout一样,所以整合后为:
var block1 = document.getElementById("block1"); var block2 = document.getElementById("block2"); var timer = null; block1.onmouseover = function(){ block2.style.display = 'block'; clearTimeout(time); } block2.onmouseout = block1.onmouseout = function(){ timer = setTimeout("block2.style.display = 'none'",1000); } block2.onmouseover = function(){ clearTimeout(timer); block2.style.display = 'block'; }
将javascript代码保存,在HTML中设置一个路径即可;