aladdinx
2016-03-19 23:30
<DOCTYPE! html>
<head>
<meta charset="utf-8">
<title>动起来</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
window.onload = function(){
var oTotal = document.getElementById('total');
oTotal.onmouseover = function(){
startMove(0);
}
oTotal.onmouseout = function(){
startMove(-150);
}
}
var timer=null;
function startMove(iTarget){
clearInterval(timer);
var oTotal = document.getElementById('total');
var speed = (iTarget-oTotal.offsetLeft)/15;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
timer = setInterval(function(){
if(oTotal.offsetLeft == iTarget){
clearInterval(timer);
}else{
oTotal.style.left=oTotal.offsetLeft+speed+'px';
}
},30);
}
</script>
</head>
<body>
<div id="total">
<div id="share">
</div>
<span>分享</span>
</body>
</html>
div标签没写好,span应该在里面,css样式定义好,注意var speed = (iTarget-oTotal.offsetLeft)/15;需要整除,因为后面if(oTotal.offsetLeft == iTarget)必须满足条件才会清除定时器,动画才会停下
<DOCTYPE! html>
<head>
<meta charset="utf-8">
<title>动起来</title>
<link rel="stylesheet" type="text/css" href="style.css">
<style type="text/css">
*{margin: 0;padding: 0;}
#total{
width: 150px;
height: 300px;
position: absolute;
left: -150px;
top: 0;
background: #9cf;
}
#share{
width: 30px;
text-align: center;
height: 60px;
line-height: 30px;
position: absolute;
left:150px;
top: 130px;
background-color: #fcc;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oTotal = document.getElementById('total');
oTotal.onmouseover = function(){
startMove(0);
}
oTotal.onmouseout = function(){
startMove(-150);
}
}
var timer=null;
function startMove(iTarget){
clearInterval(timer);
var oTotal = document.getElementById('total');
var speed = (iTarget-oTotal.offsetLeft)/15;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
timer = setInterval(function(){
if(oTotal.offsetLeft == iTarget){
clearInterval(timer);
}else{
oTotal.style.left=oTotal.offsetLeft+speed+'px';
}
},30);
}
</script>
</head>
<body>
<div id="total">
<span id="share">分享</span>
</div>
</body>
</html>
JS动画效果
113925 学习 · 1443 问题
相似问题