只需按一下按钮,CSS转换只会发生一次

时间:2013-03-23 14:24:08

标签: html5 css3 animation

我想做的是:

我正在尝试制作一个按钮控制的动画,其中一个小棒图移动到右侧或左侧,具体取决于单击哪个按钮。

问题:

  • 动画只发生一次
  • 仅适用于向右和向下按钮
  • 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>  
    

    截图

    stick man

    1 个答案:

    答案 0 :(得分:3)

    您无法将25px添加到25px作为字符串。

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

    您希望您的功能如下所示:

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

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