慕九州4321472
2016-02-27 22:14
<!DOCTYPE html>
<html>
<head>
<title>同时运动</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<style type="text/css">
*{
margin: 0;
padding: 0;
}
ul,li{
list-style: none;
}
ul li{
width:200px;
height:100px;
background: yellow;
margin-bottom: 20px;
filter:alpha(opacity:30);
opacity: 0.3;
border:1px solid #000;
}
</style>
<script type="text/javascript">
window.onload=function(){
var Li = document.getElementById('li1');
Li.onmouseover=function(){
startMove(Li,{width:300,height:200,opacity:100});
}
Li.onmouseout=function(){
startMove(Li,{width:200,height:100,opacity:30});
}
}
function startMove(obj,json,fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var flag = true;
for(var i in json){
//1.取当前的值
var icur = 0;
if(i == 'opacity'){
icur = Math.round(parseFloat(getStyle(obj,i))*100);
}else{
icur = parseInt(getStyle(obj,i));
}
//2.算速度
var speed = (json[i]-icur)/10;
speed = speed >0?Math.ceil(speed):Math.floor(speed);
//3.检测停止
if(icur != json[i]){
flag = false;
//alert(flag);
if(i == 'opacity'){
obj.style.filter = 'alpha(opacity:'+(icur+speed)+')';
obj.style.opacity = (icur+speed)/100;
}else{
obj.style[i] = icur + speed + 'px';
}
}else{
flag = true;
}
}//for结束
if(flag){
clearInterval(obj.timer);
//fn是回调函数
if(fn){
fn();
}
}
},30);
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
//return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj,false)[attr];
}
</script>
</head>
<body>
<ul>
<li id='li1'></li>
</ul>
</body>
</html>
不该在遍历内添加flag = true;的,假设有两个CSS属性,第一个icur != json[i] 这时flag =false,但是到第二个属性时如果icur == json[i],此时flag = true,将第一个false覆盖。所以不能达到想要的效果
嗯,你的改法就是老师的讲法,这个我是懂的,我上面的代码,打开调试每次width或者height的像素都达不到想要的,也想不太明白
你的问题我仔细看了看,算是自己复习一下运动框架。把你的代码在浏览器里跑了一下发现透明度没有问题,宽度和高度有两个像素差别,你的icur取值没有问题说明是在json循环里有问题,
//3.检测停止 if(icur != json[i]){ flag = false; //alert(flag); if(i == 'opacity'){ obj.style.filter = 'alpha(opacity:'+(icur+speed)+')'; obj.style.opacity = (icur+speed)/100; }else{ obj.style[i] = icur + speed + 'px'; } }else{ flag = true; } }//for结束
问题出在这儿,你把
if(i == 'opacity'){ obj.style.filter = 'alpha(opacity:'+(icur+speed)+')'; obj.style.opacity = (icur+speed)/100; }else{ obj.style[i] = icur + speed + 'px'; }
放在了if(icur != json[i])判断中,道理其实我似懂非懂,你可以按着逻辑来自己想一下,不过最后的结果是改为一下的代码就好了:
if(icur != json[i]){ flag = false; }; if(i == 'opacity'){ obj.style.filter = 'alpha(opacity:'+(icur+speed)+')'; obj.style.opacity = (icur+speed)/100; }else{ obj.style[i] = icur + speed + 'px'; } }//for结束
JS动画效果
113925 学习 · 1443 问题
相似问题