思路: 1,临界值是 -150 和 0 如果大于临界值,就要隐藏 2,隐藏:速度为负 显示:速度为正 3,如果与临界值相等,就清空定时器 否则,就运动
--------------------------------
html部分
<div id="div1"><span>分享到</span></div> <style> #div1 { position:absolute; left:-150px; 150px; height:200px; background:green;} #div1 span {position:absolute; right:-20px; top:70px; 20px; height:60px; line-height:20px; background:blue;} </style>
js部分
<script> window.onload = function(){ var oDiv = document.getElementById("div1"); var timer = null; oDiv.onmouseover = function(){ showHide(0); } oDiv.onmouseout = function(){ showHide(-150); } //展开 function show(){ clearInterval(timer); timer = setInterval(function(){ if(oDiv.offsetLeft>=0){ clearInterval(timer); }else{ oDiv.style.left = oDiv.offsetLeft + 10 + "px"; } },30); } //隐藏 function hide(){ clearInterval(timer); timer = setInterval(function(){ if(oDiv.offsetLeft==-150){ //这里是等于 clearInterval(timer); }else{ oDiv.style.left = oDiv.offsetLeft - 10 + "px"; } },30); } } </script>
优化成一个方法
//优化成一个方法 function showHide(iCritical){ clearInterval(timer); var speed; timer = setInterval(function(){ if(oDiv.offsetLeft > iCritical){ speed = -10; }else{ speed = 10; } if(oDiv.offsetLeft == iCritical){ clearInterval(timer); } else{ oDiv.style.left = oDiv.offsetLeft + speed + "px"; } },30); }