
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#p1,#p2,#p3 {
width: 200px;
height: 200px;
background: red;
margin: 10px;
}
</style>
</head>
<body>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script type="text/javascript">
var timer = null;
op = document.getElementsByTagName("p");
function test(i) {
timer = setInterval(function() {
op[i].style.height = op[i].offsetHeight + 2 + 'px'
}, 30)
};
for (var i = 0; i < 3; i++) {
op[i].onmouseover = function() {
test(i);
}
op[i].onmouseout = function() {
clearInterval(timer);
}
}
</script>
</body>
</html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
@小_秦 已经指出问题了,也提供了解决方法。我再补充两种,其他朋友如果有其他方法的话不妨贴上来。
1.楼主最好去学习一下MARKDOWN怎么写。
2.这个是闭包陷阱
你可以使用闭包实验一下你这个for绑定事件肯定不对的,绑定的i都是3所以肯定op[3]都是不存在的,
1)
p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}==》
#p1,#p2,#p3{width:200px;height:200px;background:red;margin:10px;}2)p,mouseover事件触发函数中的i为3,这里涉及到js中变量作用域
3) p的事件绑定推荐使用代理的方式-不用为每一个p绑定事件回调
timer = null; 后面应该是逗号
你声明变量时,要用var,如果是全局变量时函数内部不用var,儿最外层原始变量需要var的,这段代码,错误百出啊,以上楼层说了闭包的问题,就不多说了