多物体运动,包括透明度运动:
a)定义、获取元素;
b)定义函数,用来获取对象当前样式(非行间),参数为对象及属性名;
c)定义函数,用来使对象按照传入参数运动,参数:对象、运动目标、运动属性;
d)添加触发的事件。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>多物体运动框架</title>
<style type="text/css">
#div1{width:100px; height:100px; background:red;}
#div2{width:100px; height:100px; background:blue;}
#div3{width:100px; height:100px; background:yellow;
border:1px solid black;}
#div4{width:100px; height:100px; background:black;
opacity:0.3; filter:alpha(opacity=30);}
</style>
</head>
<body>
<div id="div1">变宽 </div>
<div id="div2">变高 </div>
<div id="div3">边框变宽 </div>
<div id="div4"><font size="" color="white">透明度</font> </div>
<input type="text" id="text1" />
<script type="text/javascript">
<!--
var div1=document.getElementById("div1");
var div2=document.getElementById("div2");
var div3=document.getElementById("div3");
var text1=document.getElementById("text1");
// 获取非行间样式
function getStyle(obj,styleName){
var speed=0;
if(obj.currentStyle){
return obj.currentStyle[styleName];
}else{
return getComputedStyle(obj,null)[styleName];
}
}
function move(obj,target,attr){
console.log("…………………………");
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var now=0; //接收当前属性值
if(attr=="opacity")
{
now=Math.round(parseFloat(getStyle(obj,attr)*100) );
}else
{
now=parseInt(getStyle(obj,attr) );
}
if(target==now) //到达目标 停止
{
clearInterval(obj.timer);
}else
{// (target-now)/n n可以自定义来调整速度快慢
speed=(target-now)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
// console.log("speed "+speed); //速度取整
if(attr=="opacity") //注意 == 双等于,不然就是赋值了
{
// console.log("进入 if");
obj.style[attr]=(now+speed)/100;
obj.filter="alpha(opacity="+(now+speed)+");";
}else
{
// console.log("进入 else");
obj.style[attr]=now+speed+"px";
}
}
text1.value=attr+" "+obj.style[attr]; //在文本框显示属性名称和值
},30); // 定时器
} // move 结束
// 给运动添加事件
div1.onmouseover=function(){
move(this,300,"width");
console.log("1调用结束");//先执行上面代码,开启定时器后间隙执行后面的代码
}
div1.onmouseout=function(){
move(this,100,"width");
}
div2.onmouseover=function(){
move(div2,400,"height");
// console.log("2调用结束");
}
div2.onmouseout=function(){
move(div2,100,"height");
}
div3.onmouseover=function(){
move(div3,40,"borderWidth");
// console.log("3调用结束");
}
div3.onmouseout=function(){
move(div3,1,"borderWidth");
}
div4.onmouseover=function(){
move(this,100,"opacity");
// console.log("4调用结束");
}
div4.onmouseout=function(){
move(this,30,"opacity");
}
//-->
</script>
</body>
</html>
注意:
①定时器分离,多个运动对象各自用一个定时,避免互相干扰;
②透明度需要与其他style单独处理,对属性值处理和style不同;
③注意获取的值进行运算时区分数据类型并转换,注意速度取整。