问答详情
源自:4-3 任意属性值(一)

为什么我的运动后的值是393和207,这差的7px是怎么回事?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        ul{
            list-style: none;
        }
        ul li{
            width:200px;
            height: 80px;
            background: red;
            margin-bottom: 20px;
            border: 4px solid black;
        }
    </style>
    <script>
        window.onload=function(){
            var Lis = document.getElementsByTagName("li");
            for (var i = 0 ; i<Lis.length;i++){
                Lis[i].timer = null;
                Lis[i].onmouseover = function(){
                    startMove(this,'width',400);
                };
                Lis[i].onmouseout = function(){
                    startMove(this,'width',200);
                }
            }

            function startMove(obj,attr,target){
                    clearInterval(obj.timer);
                    obj.timer = setInterval(function(){
                    var icur = parseInt(getStyle(obj,attr));
                    var speed = (target - icur)/8;
                    speed = speed > 0 ? Math.floor(speed) : Math.ceil(speed);
                    if(icur == target){
                        clearInterval(obj.timer);
                    }else{
                        obj.style[attr] = icur + speed + "px";
                    }
                },30)

            }
            function getStyle(obj,attr){
                if(obj.currentStyle){
                    return obj.currentStyle[attr];
                }else{
                    return getComputedStyle(obj,false)[attr];
                }
            }

        }
    </script>
</head>
<body>
<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>
</body>
</html>


提问者:qq_烟火里的尘埃_0 2015-12-25 18:31

个回答

  • ppo_YXWU
    2015-12-26 10:51:01
    已采纳

     speed = speed > 0 ? Math.floor(speed) : Math.ceil(speed);
    这一句换一下:

     speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

    这样才能保证速度不为0;不然width差值小于8时速度就为0了,width就不变了,一直达不到200和400