大神帮忙找找错,为什么说getComputedStyle在window下获取失败?

来源:5-1 JS链式动画

2393611203

2016-05-11 20:01

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>链式运动</title>
<style>
*{
	padding:0;
	margin:0;
	list-style:none;
}
#box{
	margin:0 auto;
	background:orange;
	width:200px;
	height:200px;
	opacity:0.3;
	filter:alpha(opacity:30);
	margin-bottom:20px;
}
</style>
<script>
window.onload=function(){
	var div=document.getElementById("box");
	div.onmouseover=function(){
		change(this,'width',400,function(){
			change(this,'height',400);
		});
	}
}
function getStyle(obj,attr){
	if(obj.currentStyle){
		return obj.currentStyle[attr];
	}
	else{
		return getComputedStyle(obj,false)[attr];
	}
}

function change(obj,attr,target,fn){
	clearInterval(obj.timer);

	obj.timer = setInterval(function(){
		var val = 0;
		if(attr == 'opacity'){
			val = Math.round(parseFloat(getStyle(obj,attr))*100);
		}
		else{
			val = parseInt(getStyle(obj,attr));
		}


		var speed = (target-val)/8;
		speed = speed>0 ? Math.ceil(speed) : Math.floor(speed);


		if(val == target){
			clearInterval(obj.timer);
//判断是否传入了fn
			if(fn){
				fn();
			}
		}
		else{
			if(attr == 'opacity'){
				obj.style.filter = 'alpha(opacity:' + val+speed + ')';
				obj.style.opacity = (val+speed)/100;
			}
			else{
				obj.style[attr] = val + speed +"px";
			}
		}
	},30)
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>


写回答 关注

4回答

  • 慕移动9181930
    2022-03-25 05:21:44
  • 酋长最帅
    2016-06-19 18:59:04

    别直接用This,将this赋值给一个变量,如var that=this;

  • 左手键盘右手鼠标
    2016-05-31 16:08:19

    但是如果是for循环里面的话  this就不能改啊

  • joffyzou
    2016-05-12 14:32:44
    window.onload=function(){
        var div=document.getElementById("box");
        div.onmouseover=function(){
            change(this,'width',400,function(){
                change(this,'height',400);
            });
        }
    }

    这里的外层change()可以传this,但是到了里层change()时,this就代表window对象了。可以改成div

JS动画效果

通过本课程JS动画的学习,从简单动画开始,逐步深入各种动画框架封装

113923 学习 · 1443 问题

查看课程

相似问题