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

I want my animation to travel horizontally across the screen and stop once i press the stop button

本文关键字:按钮 移动 动画 我的 屏幕 我希望 水平      更新时间:2023-09-26

我想在这里做几件事:

"

开始"按钮启动动画,然后变为"停止"按钮。然后停止按钮在动画所在的位置停止动画并变回"开始"按钮,使我能够从停止的位置恢复。

相反,一旦我再次按下开始或停止,动画就会消失。

对于这种事情,我是一个新手,如果我不清楚我的意图,请告诉我,我会尽力澄清它。

<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>

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

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

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

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

  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>

您的 CSS:

#object {
    position: absolute;
    left: 0px;
    bottom: 100px;
    width: 100px;
    height: 100px;
}

最后是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%'});
}

这是一个小提琴,您可以在其中看到"动作"。