<!DOCTYPE HTML>
<html lang="en/zh">
<head>
<meta charset="UTF-8">
<title>JS_动画任意属性值一</title>
<style type="text/css">
*{
padding: 0px;
margin: 0px;
}
#div1{
width: 200px;
height: 200px;
background: red;
border: 2px solid blue;
filter:alpha(opacity:30); /*ie低版本不支持opacity的 只支持filter */
opacity: 0.3; /*firefox,chrome*/
}
</style>
<script type="text/javascript">
window.onload=function(){
var div1=document.getElementById("div1");
div1.onmouseover=function(){
move(this,"opacity",100);
}
div1.onmouseout=function(){
move(this,"opacity",30);
}
}
/*动画函数*/
var timer=null;
var speed=0;
function move(obj,attr,target){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var speed=0;
var cur=0;
if (attr=="opacity") {
cur=Math.round(parseFloat(getStyle(obj.attr))*100);
}else{
var cur=parseInt(getStyle(obj,attr));
}
var speed=(target-cur)/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(cur==target){
clearInterval(obj.timer);
}else{
if (attr=="opacity"){
obj.style.filter="alpha(opacity:"+(cur+speed)+")";
obj.style.opacity=(cur+speed)/100;
}else{
obj.style[attr]=cur+speed+"px";
}
}
},30);
}
/*获取样式函数*/
function getStyle(obj,attr){
if (obj.currentStyle) {
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>