js运动:分享到

时间:2022-06-07 15:07:34

定时器及运动函数的使用。

js运动:分享到

<!--
Author: XiaoWen
Create a file: 2016-12-14 09:41:11
Last modified: 2016-12-14 10:11:53
Start to work:
Finish the work:
Other information:
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分享到</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
position: fixed;
top: 40px;
left: -100px;
background: #ccc;
}
#box .share{
width: 20px;
height: 60px;
background: #f00;
position: absolute;
right: -20px;
top: 20px;
}
</style>
</head>
<body>
<div id="box">
<div class="share">分享到</div>
</div>
<script>
var box=document.getElementById("box");
var share=box.getElementsByClassName("share")[0];
box.onmouseover=function(){
move(box,'left',0)
}
box.onmouseout=function(){
move(box,'left',-100)
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj)[attr];
}
}
var timer=null;
function move(obj,attr,iTarget){
clearInterval(obj.timer)
obj.timer=setInterval(function(){
var speed=(iTarget-parseInt(getStyle(obj,attr)))/8;
speed=speed>0 ? Math.ceil(speed) : Math.floor(speed);
if(iTarget==parseInt(getStyle(obj,attr))){
clearInterval(obj.timer);
}else{
obj.style[attr]=parseInt(getStyle(obj,attr))+speed+'px';
}
},10)
}
</script>
</body>
</html>