三个正方形方块,鼠标滑过会改变宽高透明度,为什么写成for循环就不能运行,而分开写就能正常运行呢
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>透明度运动</title>
<script src="js/move.js"></script>
</head>
<style type="text/css">
body,div{
margin: 0;
padding: 0;
}
li{
list-style:none;
width: 200px;
height: 200px;
background: red;
margin-bottom:20px;
filter:alpha(opacity:70);
opacity:0.3;
border:2px solid black;
fontSize:30px;
}
</style>
<script type="text/javascript">
window.onload=function()
{
var lis = document.getElementsByTagName("li");
var uls = document.getElementsByTagName("ul");
//为什么写成for循环就不能运行,而分开写就能正常运行呢
for(var j=0; j<lis.length; j++)
{
lis[j].indexTimer = null;
lis[j].onmouseover=function(){
move(lis[j],{width:400, height:400, opacity:100})};
lis[j].onmouseout=function(){
move(lis[j],{width:200, height:200, opacity:30})};
}
/*lis[0].indexTimer = null;
lis[1].indexTimer = null;
lis[2].indexTimer = null;
lis[0].onmouseover=function(){
move(lis[0],{width:400, height:400, opacity:100})};
lis[0].onmouseout=function(){
move(lis[0],{width:200, height:200, opacity:30})};
lis[1].onmouseover=function(){
move(lis[1],{width:400, height:400, opacity:100})};
lis[1].onmouseout=function(){
move(lis[1],{width:200, height:200, opacity:30})};
lis[2].onmouseover=function(){
move(lis[2],{width:400, height:400, opacity:100})};
lis[2].onmouseout=function(){
move(lis[2],{width:200, height:200, opacity:30})};*/
}
function move(obj,json,fn)//
{
clearInterval(obj.indexTimer);//清除每个li的定时器
obj.indexTimer=setInterval(
function()
{
var getArr = 0;
var flag = true;
for(var attr in json)
{
//取属性值
if(attr=="opacity")
{
getArr =Math.round((parseFloat(getStyle(obj,attr)))*100);
}
else
{
getArr=parseInt(getStyle(obj,attr));
}
//根据目标值计算速度
var speed=(json[attr]-getArr)/20;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(attr=="opacity")
{
obj.style.opacity =(getArr+speed)/100;
obj.style.filter = "alpha(opacity:'+(getArr+speed)+')" ;
}
else{ obj.style[attr] = getArr+speed + "px";}
if(getArr!=json[attr])
{
flag=false;
}
}
if(flag == true)
{
clearInterval(obj.indexTimer);
if(fn){fn();};
}
},30);
}
function getStyle(obj,attr)
{
if(obj.currentStyle)
{
return obj.currentStyle[attr];
}
else
{
return getComputedStyle(obj,false)[attr];
}
}
</script>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
</html>