猿问

left值不一样

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>缓冲1</title>
    <style type="text/css">
        #div1{height: 200px;
          width: 200px;
          background: blue;
          position: relative;
          left: -200px;
          }
        #div1 span{   position: absolute;
            height: 50px;
            width: 15px;
            left: 200px;
            top: 75px;
            background-color: red;
            }
        *{margin: 0;padding: 0;}
    </style>
    <script type="text/javascript">
    window.onload=function () {
        var div1=document.getElementById('div1');
            div1.onmouseover=function(){
                startmove(0);
            }
            div1.onmouseout=function(){
                startmove(-200);
            }
    }

    var timer=null;
    function startmove (itarget) {
        clearInterval(timer);
        timer=setInterval(function(){
            var speed=(itarget-div1.offsetLeft)/20;//speed赋值后,下边接着判断
            speed=speed>0?Math.ceil(speed):Math.floor(speed);
            if (itarget==div1.offsetLeft) {
                    clearInterval(timer);
            } else{
                div1.style.left=div1.offsetLeft+speed+'px';
            };

        },30)
    }

    </script>
</head>
<body>
    <div id="div1">
        <span>分享</span>
    </div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>缓冲2</title>
    <style type="text/css">
        #div1{height: 200px;
          width: 200px;
          background: blue;
          position: relative;
          left: -200px;
          }
        #div1 span{   position: absolute;
            height: 50px;
            width: 15px;
            left: 200px;
            top: 75px;
            background-color: red;
            }
        *{margin: 0;padding: 0;}
    </style>
    <script type="text/javascript">
    window.onload=function () {
        var div1=document.getElementById('div1');
            div1.onmouseover=function(){
                startmove(0);
            }
            div1.onmouseout=function(){
                startmove(-200);
            }
    }

    var timer=null;
    function startmove (itarget) {
        clearInterval(timer);
        timer=setInterval(function(){//这里speed直接赋值并且判断
            var speed=speed>0?Math.ceil((itarget-div1.offsetLeft)/20):Math.floor((itarget-div1.offsetLeft)/20);
            if (itarget==div1.offsetLeft) {
                    clearInterval(timer);
            } else{
                div1.style.left=div1.offsetLeft+speed+'px';
            };

        },30)
    }

    </script>
</head>
<body>
    <div id="div1">
        <span>分享</span>
    </div>
</body>
</html>

两种speed的赋值方式,造成两种结果:第一段代码向右移动后的left值正常,能达到0;第二段代码向右移动后的left值是-19px.

周末00
浏览 1574回答 2
2回答

echo_kinchao

逻辑出现了问题

忧郁的狮子座

因为19除以20等于0。因此,当offsetleft小于20,比如19的时候,speed就为0了,当然就不动咯。反过来增加的话,就不会出现这种情况。
随时随地看视频慕课网APP
我要回答