1

我想做的是:

我正在尝试制作一个按钮控制的动画,其中一个小棒图根据单击的按钮向右或向左移动。

问题:

  • 动画只发生一次
  • 仅适用于向右和向下按钮
  • HTML:

    <!DOCTYPE html>
    <html>
    
    <style>
        #stage{
            width: 100px;
            height: 100px;
            position: relative;
            border-style: dashed;
            border-color: gray;
            border-width: medium;
        }
    
        #actor{
            width: 13px;
            height: 15px;
            position: absolute;
            left: 0;
            top: 0;
            background-image: url("E:/Website Projects/man.PNG");
    
            -webkit-transition: all 2s ease-out 0s;
            -moz-transition: all 2s ease-out 0s;
            transition: all 2s ease-out 0s;
        }
    
    
    </style>
    
    <body>
        <div id="stage">
            <div id="actor"></div>
        </div>
    
        <div>
            <button class="control" id="top">TOP</button> <br>
            <button class="control" id="left">LEFT</button> <button class="control" id="right">RIGHT</button> <br>
            <button class="control" id="down">DOWN</button>
        </div>
    </body>
    
    <script>
        var maxWidth = 100;
        var maxHeight = 100;
    
        var top = document.querySelector("#top");
        var left = document.querySelector("#left");
        var right = document.querySelector("#right");
        var down = document.querySelector("#down");
    
        top.addEventListener("click",moveTop,false);
        left.addEventListener("click",moveLeft,false);
        right.addEventListener("click",moveRight,false);
        down.addEventListener("click",moveDown,false);
    
        function moveTop(){
            var actor = document.querySelector("#actor");
            actor.style.top -= "25px";
        }
    
        function moveDown(){
            var actor = document.querySelector("#actor");
            actor.style.top += "25px";
        }
    
        function moveRight(){
            var actor = document.querySelector("#actor");
            actor.style.left += "25px";
        }
    
        function moveLeft(){
            var actor = document.querySelector("#actor");
            actor.style.left -= "25px";
        }
    
    </script>
    
    </html>  
    

    截屏

    棍子人

    4

    1 回答 1

    3

    您不能添加25px25px字符串。

    您只能将+=and-=用于整数。

    你会希望你的函数看起来像这样:

    function moveDown(){
        var actor = document.querySelector("#actor");
        var num = parseInt(actor.style.top) || 0;
        actor.style.top = num + 25 + "px";
    }
    

    工作示例:http: //jsfiddle.net/5CMWW/

    于 2013-03-23T14:29:25.043 回答