美文网首页
方块左右移动

方块左右移动

作者: 书童drj | 来源:发表于2017-06-27 12:02 被阅读0次
    <body>
        <button>move-right</button>
        <button>move-left</button>
        <div id="box"></div>
    </body>
    
    <style>
        body{
            margin: 0;
        }
        #box{
            position: absolute;
            left: 10px;
            background-color: red;
            width: 100px;
            height: 100px;
            box-sizing: border-box;
        }
    </style>
    
    <script>
            window.onload = function(){
                var box = document.getElementById('box');
                var btn1 = document.getElementsByTagName('button')[0];
                var btn2 = document.getElementsByTagName('button')[1];
                btn1.onclick = function(){  
                    move(box,500);
                }
                btn2.onclick = function(){
                    move(box,10);
                }
    
                var time = null;
                var speed = null;
                function move(elem,itarget){
                    clearInterval(time);
                    time = setInterval(function(){
                    speed = (itarget-elem.offsetLeft)/20;
                        if(speed>0){
                            speed = Math.ceil((itarget-elem.offsetLeft)/20);
                        }else{
                            speed = Math.floor((itarget-elem.offsetLeft)/20);
                        }
                        if(parseInt(elem.style.left)==itarget){
                            clearInterval(time);
                        }else{
                            elem.style.left = elem.offsetLeft + speed + "px";
                        }
                    }, 30)
                }
             }
    </script>
    

    相关文章

      网友评论

          本文标题:方块左右移动

          本文链接:https://www.haomeiwen.com/subject/wzzscxtx.html