如果瀏覽器不支持小數(shù)像素,var speed = (iTarget - oDiv.offsetLeft)/20;當(dāng)speed等于20以下的時(shí)候,oDiv.style.left = oDiv.offsetLeft + speed +'px';這里的speed就小于1了。瀏覽器應(yīng)該在20px左右的時(shí)候就停止了,為什么是在10px左右的時(shí)候停止呢
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body,div,span{
margin: 0;
padding: 0;
}
? ?#div1{
? ? width: 200px;
? ? height: 200px;
? ? left: -200px;
? ? background-color: red;
? ? position: relative;
? ?}
#div1 span{
width: 20px;
height: 50px;
background-color: blue;
position: absolute;
top:75px;
left: 200px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oDiv = document.getElementById('div1');
oDiv.onmouseover = function () {
startMove(0);
}
oDiv.onmouseout = function () {
startMove(-200);
}
}
var timer = null;
function startMove(iTarget) {
clearInterval(timer);
var oDiv = document.getElementById('div1');
timer = setInterval(function () {
var speed = (iTarget - oDiv.offsetLeft)/20;
if (oDiv.offsetLeft == iTarget) {
clearInterval(timer);
} else {
oDiv.style.left = oDiv.offsetLeft + speed +'px';
}
},30)
}
</script>
</head>
<body>
<div id="div1">
<span id="share">分享</span>
</div>
</body>
</html>
如果瀏覽器不支持小數(shù)像素,var speed = (iTarget - oDiv.offsetLeft)/20;當(dāng)speed等于20以下的時(shí)候,oDiv.style.left = oDiv.offsetLeft + speed +'px';這里的speed就小于1了。瀏覽器應(yīng)該在20px左右的時(shí)候就停止了,為什么是在10px左右的時(shí)候停止呢
2016-09-19
我猜是因?yàn)橄袼赜行?shù)時(shí)會(huì)四舍五入,所以speed小于1大于0.5時(shí)還會(huì)動(dòng),10px左右的時(shí)候停止是剛好speed在0.5的分界線
2016-09-19
看教程