我希望我的动画在屏幕上水平移动,并在按下停止按钮后停止

aAl*_*mov 5 javascript jquery animation

我想在这里做几件事:

"开始"按钮启动动画,然后变为"停止"按钮.停止按钮然后停止动画,然后转回"开始"按钮,让我从停止的位置恢复.

相反,一旦按下开始或停止,动画就会消失.

当谈到这种东西时,我是新手,如果我不清楚我的意图请告诉我,我会尽力清理它.

<html>
<head>
    <meta charset="UTF-8">
    <style>
        div {left: 0px;
             bottom: 100px;}
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script> 
        $(document).ready(function(){
            move();
            Stop();
            });
        function move(){
          $("input").click(function(){
              $(this).val('Stop');
            $("div").css({left:'0%'}).animate({left:'100%'},1000, Stop);
              Stop();
          });
        }
        function Stop(){
          $("input[value='Stop']").click(function(){
              $( ":animated" ).stop(true, true, false);
              $(this).val('Start');
              move();
        });
        }
    </script> 
</head>
<body>        
    <h1 style="text-align:center"> Welcome to the test</h1>
    <input type='button' value='Start' id='oneButton'>
    <div style="height:100px;width:100px;position:absolute;">
        <img id='myRobot' src='myRobot.jpg' width="250px" height="200px"/>
    </div>    
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Dim*_*13i 3

你的 JavaScript 代码有点混乱。首先你的移动功能:

function move(){
    $("input").click(function(){
        $(this).val('Stop');
        $("div").css({left:'0%'}).animate({left:'100%'},1000, Stop);
        Stop();
    });
}
Run Code Online (Sandbox Code Playgroud)

当div动画时,将调用您的Stop函数(不是设置为 animate 函数的回调函数的函数) 。你不想要这个。

您可能想要的本质上是三个不同的功能:

  1. 移动
  2. 暂停
  3. 重置

您的移动函数本质上将开始移动您的对象,暂停显然会暂停它,而重置会将您的对象置于初始位置,如果您愿意的话。

假设您的 HTML 文件的结构如下:

<h1 style="text-align:center"> Welcome to the test</h1>
<input type='button' value='Start' id='oneButton' />
<div id="object">
    <img id='myRobot' alt='test' src='http://www.clker.com/cliparts/7/b/d/b/1237099752389782475nicubunu_Soccer_ball.svg.thumb.png'/>
</div>
Run Code Online (Sandbox Code Playgroud)

你的CSS:

#object {
    position: absolute;
    left: 0px;
    bottom: 100px;
    width: 100px;
    height: 100px;
}
Run Code Online (Sandbox Code Playgroud)

最后是 JS:

var animating = false;

$("#oneButton").on("click", function() {
    if (!animating) {
        $(this).val("pause");
        move();
    } else {
        $(this).val("start");
        pause();
    }
});

function move() {
    animating = true;
    $("#object").animate({left:'100%'},1000, reset);
}

function pause() {
    $("#object").stop();
    animating = false;
}

function reset() {
    animating = false;
    $("#object").css({left: '0%'});
}
Run Code Online (Sandbox Code Playgroud)

这是一个FIDDLE,您可以在“操作”中看到。