在window.onload部分,遍历img标签时,把每个标签单独写动画能出现动态效果,但合成for循环就不行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动画案例</title>
<style>
div{
margin: 20px;
padding: 20px;
}
img{
width: 130px;
height: 100px;
margin: 2px;
opacity: 1;
filter: alpha(opacity:100);
position: relative;
top:20px;
display: inline-block;
}
</style>
<script>
window.onload = function () {
var allImgs = document.getElementsByTagName('img');
//for循环中不能出现动态效果
for(var i=0;i<allImgs.length;i++){
allImgs[i].timer = null;
allImgs[i].onmouseover = function () {
onMove(allImgs[i],{'top':-20,'opacity':0},function () {
allImgs[i].style.top = '30px';
onMove(allImgs[i],{'top':20,'opacity':100});
});
}
}
/*
//每一项写出来能出现动态效果
allImgs[0].timer = null;
allImgs[0].onmouseover = function () {
onMove(allImgs[0],{'top':-20,'opacity':0},function () {
allImgs[0].style.top = '30px';
onMove(allImgs[0],{'top':20,'opacity':100});
});
}
allImgs[1].timer = null;
allImgs[1].onmouseover = function () {
onMove(allImgs[1],{'top':-20,'opacity':0},function () {
allImgs[1].style.top = '35px';
onMove(allImgs[1],{'top':20,'opacity':100});
});
}
*/
}
</script>
</head>
<body>
<div id="div1">
<img src="http://img2.mukewang.com/57466d580001d46806000338-240-135.jpg" class="imgs">
<img src="http://img2.mukewang.com/57466d580001d46806000338-240-135.jpg" class="imgs">
</div>
</body>
</html>
<script>
function onMove(obj,json,fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var flag = true; //设置flag,标注是否所有属性改变完全
for(var attr in json){
if(attr == 'opacity'){
var icur = Math.round(100*getStyle(obj,attr));
}else {
var icur = getStyle(obj,attr);
}
if(icur!=json[attr]){
flag = false;
//var speed = (json[attr]>icur)?10:-10; //变化速度
var speed = (json[attr]-icur)/8;
speed = (speed>0)?Math.ceil(speed):Math.floor(speed);
if(attr == 'opacity'){
obj.style[attr] = (icur + speed)/100;
obj.style['filter'] = 'alpha(opacity:'+(icur+speed)+')';
}else {
obj.style[attr] = icur + speed + 'px';
}
}
}
if(flag == true){
clearInterval(obj.timer);
if(fn){
fn();
}
}
},30)
}
function getStyle(obj,attr) {
//返回属性值,int或者float
if(document.currentStyle){
var res = currentStyle(obj)[attr]; //IE
}
else {
var res = getComputedStyle(obj,null)[attr]; //Firefox
}
if(attr == 'opacity'){
return parseFloat(res);
}else{
return parseInt(res);
}
}
</script>
刚看到闭包,果然是这个问题
这样写就好了,因为像你之前那样写的话,函数执行完,i就永远等于2了