说明:
1,单定时器会存在问题,需要给每个元素加入定时器(关闭和打开定时器都互不干扰);
2,多物体运动框架中,所有东西都不能共用,把定义的变量作为属性加到元素身上;
3,offsetWidth或offsetHeight等获取的是盒模型的尺寸,需要考虑padding border等,获取样式方式由offset变为 obj.style['width']方式;
4,封装获取样式的js函数getCssStyle();
html:
<div id="div1"></div>
<div id="div2"></div>
<div id="div3">dddddd</div>
<div id="div4"></div>
css:
div {
width: 100px;
height: 100px;
background: black;
margin: 20px;
}
#div4{
border:4px solid yellow;
/* filter: alpha(opacity:30); */
opacity:0.3;
}
JS:
<script>
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var div4 = document.getElementById('div4');
var timer = null;
div1.onmouseover=function(){
startMove(this,'width', 400)
}
div1.onmouseout=function(){
startMove(this,'width', 50)
}
div2.onmouseover=function(){
startMove(this,'height', 400)
}
div2.onmouseout=function(){
startMove(this,'height', 50)
}
div3.onmouseover=function(){
startMove(this,'fontSize', 40)
}
div3.onmouseout=function(){
startMove(this,'fontSize', 10)
}
div4.onmouseover=function(){
startMove(this,'opacity', 1000)
}
div4.onmouseout=function(){
startMove(this,'opacity', 800)
}
function getCssStyle(obj,name){
return obj.currentStyle?obj.currentStyle[name]:getComputedStyle(obj,false)[name];
}
function startMove(obj,value,target){
clearInterval(obj.timer);
obj.timer=setInterval(function (){
var cur=0;
if(cur == 'opacity'){
cur=Math.round(parseFloat(getCssStyle(obj,value))*100);
}else{
cur=parseInt(getCssStyle(obj,value));
}
var speed=(target-cur) / 10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(cur == target){
clearInterval(obj.timer);
}else{
if(value == 'opacity'){
obj.style.filter='alpha(opacity:' + (cur + speed) + ')';
obj.style.opacity= (cur + speed) / 100;
}else{
obj.style[value]=cur + speed + 'px';
}
}
},30)
}
</script>