window.onload=function(){
startMove();
}
function getstyle(obj,attr){
if(getComputedStyle){
return getComputedStyle(obj,null)[attr]; //要return 才行,不然就是Undefined;
}
else{
return obj.currentStyle[attr];//要return 才行,不然就是Undefined;
}
}
function startMove(obj,attr,itarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var speed = (itarget - getstyle(obj,attr))/8;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
var anum = 0;
if(anum == 'opacity'){
anum = Math.round(parseFloat(getstyle(obj,attr))*100);
}
else{
anum = parseInt(getstyle(obj,attr));
}
if(anum==itarget){
clearInterval(obj.timer);
}
else{
if(arrt =='opacity'){
anum = anum +speed;
obj.style.opacity = anum/100;
obj.style.filter = 'alpha(opacity:'+anum+')';
}
else{
obj.style[attr] = anum+speed+"px";
}
}
},30)
}
下面是HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div{
width:100px;
height:100px;
background:pink;
opacity:0.3;
filter:alpha(opacity:30);
}
</style>
<script src="kuangjia.js"></script>
<script>
window.onload = function(){
var div1 =document.getElementById("div1");
div1.onmouseover = startMove(this,'width',200);
div1.onmouseout = startMove(this,'width',100);
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
var speed = (itarget - getstyle(obj,attr))/8;这一句有错
getstyle(obj,"width")返回的是100px;而不是整数100,所以itarget (整数)无法与100px相减
需要讲getstyle(obj,attr)改成 parseInt(getstyle(obj,attr))