求問(wèn):有時(shí)候當(dāng)鼠標(biāo)移入他不會(huì)停下來(lái),會(huì)一直往前走,突然又跑回來(lái)了;有一兩次正正常的。
<DOCTYPE! html>
<head>
?<meta charset="utf-8">
?<title>動(dòng)起來(lái)</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>
2016-03-21
div標(biāo)簽沒(méi)寫(xiě)好,span應(yīng)該在里面,css樣式定義好,注意var speed = (iTarget-oTotal.offsetLeft)/15;需要整除,因?yàn)楹竺鎖f(oTotal.offsetLeft == iTarget)必須滿足條件才會(huì)清除定時(shí)器,動(dòng)畫(huà)才會(huì)停下
2016-03-21
<DOCTYPE! html>
<head>
?<meta charset="utf-8">
?<title>動(dòng)起來(lái)</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>