為什么一定要用math.ceil向上取整才正確?
<!DOCTYPE html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<title>緩沖動(dòng)畫效果</title>
? ?<style type="text/css">
#div1{
? ? ? ? ? ?width: 200px;
? ? ? ? ? ?height: 200px;
? ? ? ? ? ?position: absolute;
? ? ? ? ? ?top: 0px;
? ? ? ? ? ?left: -200px;
? ? ? ? ? ?background-color: #b10d1c;
? ? ? ?}
? ? ? ?#share{
? ? ? ? ? ?width: 30px;
? ? ? ? ? ?height: 50px;
? ? ? ? ? ?position: absolute;
? ? ? ? ? ?left: 200px;
? ? ? ? ? ?top: 75px;
? ? ? ? ? ?background-color: #3c6dcb;
? ? ? ? ? ?color: #ffffff;
? ? ? ? ? ?text-align: center;
? ? ? ? ? ?cursor: pointer;
? ? ? ?}
? ?</style>
? ?<script type="text/javascript">
window.onload=function () {
var odiv1=document.getElementById('div1'),
share=document.getElementById('share');
odiv1.onmouseover=function(){
startMove(10,0);
? ? ? ? ? ?}//最好使用匿名函數(shù)來(lái)調(diào)用函數(shù)
// ? ? ? ? ? ?odiv1.onmouseout="startMove(10,0)";
odiv1.onmouseout=function(){
startMove(10,-200);
? ? ? ? ? ?}
var timer=null
? ? ? ? ? ?function startMove(speed,itarget) {
clearInterval(timer);
timer=setInterval(function () {
speed=(itarget-odiv1.offsetLeft)/10;
if(odiv1.offsetLeft==itarget){
clearInterval(timer)
? ? ? ? ? ? ? ? ? ?}
else {
if(odiv1.offsetLeft>itarget){
speed=(odiv1.offsetLeft-itarget)/10;
// ? ? ? ? ? ? ? ? ? ? ? ? ? ?speed=speed>0?Math.ceil(speed):Math.floor(speed);
speed=Math.ceil(speed);
odiv1.style.left=odiv1.offsetLeft+(-speed)+'px';
? ? ? ? ? ? ? ? ? ? ? ?}
else{
speed=(itarget-odiv1.offsetLeft)/10;
// ? ? ? ? ? ? ? ? ? ? ? ? ? ?speed=speed>0?Math.ceil(speed):Math.floor(speed);
speed=Math.ceil(speed);
odiv1.style.left=odiv1.offsetLeft+speed+'px';
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?},30);
? ? ? ? ? ?}
? ? ? ?}
</script>
</head>
<body>
<div id="div1"><span id="share">分享</span> </div>
</body>
</html>
2016-06-01
如果(目標(biāo)值-當(dāng)前值)/10 ?不能整除的話。運(yùn)動(dòng)到最后,是1~9之間的數(shù)字來(lái)除以10,結(jié)果是個(gè)小于1的小數(shù),如果向下取整,那就是0,speed=0,意味著不再發(fā)生變化。也就是說(shuō),如果用Math.floor(speed),最后不到10個(gè)像素的時(shí)候,就不會(huì)動(dòng)了。