慕粉4203582
2016-10-31 17:49
function jianjie()
{
var ms=document.getElementsByTagName('span');
var obtn=document.getElementsByTagName('input');
var i=0;
for (var i = 0; i < obtn.length; i++)
{
obtn[i].index = i;
obtn[i].onclick= function ()
{
ms[this.index].style.display = 'block';
}
obtn[i].onmouseout=function ()
{
setTimeout(obtn[this.index].onmouseout=function () //这句按道理应该是setTimeout(function (),但是写成这样就不能运行了。
{
ms[this.index].style.display = 'none';
},3000);
}
}
}
//主要目的是第三个input控制第三个SPAN的延迟隐藏与显示。
按照你的思路写了个完整的,应该是这样,几个改动地方有注释:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> </head> <body> <div style="width:100px;height:100px;"> <span>234234</span> </div> <input type="button"> <script> function jianjie() { var ms = document.getElementsByTagName('span'); var obtn = document.getElementsByTagName('input'); var i = 0; var timer for (var i = 0; i < obtn.length; i++) { obtn[i].index = i; obtn[i].onclick = function () { clearTimeout(timer); //保证点击时不会隐藏 ms[this.index].style.display = 'block'; } obtn[i].onmouseout = function () { clearTimeout(timer); //每次移出时确保只执行一个定时器 var a = this.index //将this.index用a变量来保存,因为this.index只有在事件触发时才会有值,如果设置了settimeout就是undefined,因此用变量将它保存起来 timer = setTimeout(function () { ms[a].style.display = 'none'; }, 3000); } } } jianjie() </script> </body> </html>
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> </head> <body> <div style="width:100px;height:100px;"> <span>234234</span> </div> <input type="button"> <div style="width:100px;height:100px;"> <span>234234</span> </div> <input type="button"> <div style="width:100px;height:100px;"> <span>234234</span> </div> <input type="button"> <script> function jianjie() { var ms = document.getElementsByTagName('span'); var obtn = document.getElementsByTagName('input'); var i = 0; var timer for (var i = 0; i < obtn.length; i++) { obtn[i].index = i; obtn[i].onclick = function () { clearTimeout(obtn[this.index].timer); //保证点击时不会隐藏 ms[this.index].style.display = 'block'; } obtn[i].onmouseout = function () { clearTimeout(obtn[this.index].timer); //每次移出时确保只执行一个定时器 var a = this.index //将this.index用a变量来保存,因为this.index只有在事件触发时才会有值,如果设置了settimeout就是undefined,因此用变量将它保存起来 obtn[this.index].timer = setTimeout(function () { ms[a].style.display = 'none'; }, 3000); } } } jianjie() </script> </body> </html>
JavaScript进阶篇
468061 学习 · 21891 问题
相似问题