js运动相关代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin: 0px;padding: 0px;}
#t{width: 130px;height: 130px;background: red;position: absolute;
left: -130px;top: 200px;
}
#d{width: 30px;height: 50px;background: black;position: absolute;left: 130px;top: 35px;color: white;text-align: center;cursor:pointer;}
#t1{width: 130px;height: 130px;background: green;position: absolute;left: 300px;top: 60px;}
#t4{
width: 130px;height: 130px;background: green;position: absolute;left: 300px;top: 200px;opacity: 0.3;}
}
</style>
</head>
<body>
<div id="t4"></div>
<div id="t">
<div id="d">分享</div>
</div>
<div id="t1"></div>

<script>
var t=document.getElementById("t");
var d=document.getElementById("d");
var t1=document.getElementById("t1");
function getArr(){
arr=[];
for(var i=16;i>0;i-=2){
arr.push(-i);
arr.push(i);
}
arr.push(0);
return arr;
}
t1.onmouseover=function(){
this.style.cursor="pointer";
doMove(this,"top",getArr(),20,-130,60);
}
d.onmouseover=function(){
if(!t.index){ //undefined==false的结果是false
doMove(t,"left",10,20,-0);
t.index=true;
}else{
doMove(t,"left",-10,20,-130);
t.index=false;
}
}
var t4=document.getElementById("t4");

t4.onmouseover=function(){
doMove(this,'opacity',0.2,100,1);
}
t4.onmouseout=function(){
doMove(this,'opacity',-0.2,300,0.3);
}
/* e是元素,s是元素的属性,p是元素运动的步长,(可以是同一速度就传递一个数.不同的速度可以传递一个数组)
h是元素运动的频率,t是目标点,fun是回调函数
次函数可以省略最后两个参数,这样的话就没有目标点啦
tl参数是确定元素的初识位置,防止不在原来的位置
*/
/*使用此函数要事先手动指定元素的位置.*/
function doMove(e,s,p,h,t,tl,fun){
clearInterval(e.timer);
var i=0;
if(tl==0||tl){
e.style[s]=tl+'px';//防止抖动的时候脱离原来的位置.所以先要确定初始位置
}
e.timer=setInterval(function(){
var d=p instanceof Array?p[i]:p;//判断传的步长是数组还是数字
i++;
var speed2=Math.round(getStyle(e,"opacity")*100)+d*100;
/*注意对于透明度的问题涉及到小数,所以就会有精度不准的问题,所以让透明度乘以100变成整数,speed2是透明度的大小*/
/*兼容谷歌的旧版本Math.round()*/
var speed1=parseInt(getStyle(e,s))+d;
if(/*(t||t==0)&&*/speed1>t&&p>0){//注意这里当目标点为0的时候js自动将其转化为false.因为当元素贴上浏览器左边界时,left的值为0,但不是false
speed1=t;
}
if(/*(t||t==0)&&*/speed1<t&&p<0){speed1=t;}
if(speed2>t*100 && s=="opacity"){speed2=t*100;}
if(s=="opacity" || s=="filter"){
e.style[s]=speed2/100;
e.style.filter = 'alpha(opacity='+ speed2 +')';//兼容IE低版本
}else{
e.style[s]=speed1+"px";
}

if((t||t==0)&&speed1==t ||i==p.length && p instanceof Array ||speed2==t*100){
clearInterval(e.timer);
fun && fun();//函数执行完后要执行的函数
}
},h);
}
function getStyle(e,s){
return e.currentStyle?e.currentStyle[s]:getComputedStyle(e)[s];
}
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/weikemudan/p/10297767.html