function getStyle(obj,attr){
if(obj.currentStyle)
{
return obj.currentStyle[attr];
}
else
{
return getComputedStyle(obj,false)[attr];
}
}
function startMove(obj,json,fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
for(var attr in json){
var iCur = 0;
var flag = true;
if(attr == 'opacity'){
iCur = Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
iCur = parseInt(getStyle(obj,attr));
}
var speed = (json[attr]-iCur)/8;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(iCur != json[attr]){
flag = false;
}
if(attr == 'opacity'){
obj.style.opacity = (iCur + speed)/100;
obj.style.filter = 'alpha(opactiy:'+(iCur+speed)+')';
}else{
obj.style.attr = iCur + speed + 'px';
}
if(flag){
clearInterval(obj.timer);
if(fn){
fn();
}
}
}
}
,30)
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="move.js"></script>
<script>
window.onload = function(){
var div = document.getElementById('box');
div.onmouseover = function(){
startMove(div,{opacity:100,width:400,height:400});
}
}
</script>
<style>
#box{
width: 300px;
height: 300px;
background-color: green;
opacity:0.3;
filter:alpha(opactiy:30);}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>
问一下为什么只修改了opacity的值 没有改变width和height呢?
if(attr == 'opacity'){
obj.style.opacity = (iCur + speed)/100;
obj.style.filter = 'alpha(opactiy:'+(iCur+speed)+')';
}else{
obj.style.attr = iCur + speed + 'px'; //问题大概在这里
}
正确的写法是obj.style[attr]才对吧。
另外,css3动画那么好用,为毛还要自己费事写这个?
因为你的attr
是变量,无法通过obj.style.attr
来赋值,要使用obj.style[attr]
才行。
obj.style[attr]正解
用CSS3动画好,很多js运动插件都是优先使用CSS3的特性,不支持CSS3的采用JS去兼容,js动画效果很生硬,例如jQuery
@sirqiao的obj.style[attr]
是正解哦!
关于用CSS3动画还是JS实现,还是看需求和自己手上的技能咯。
你把position设置为absolute