我在做作业时遇到一些问题。无论如何,当我使用startInterval时,我会分配和intervalID,以便以后可以清除间隔。不幸的是,当您按下“停止这种疯狂”按钮时,它并不清楚。有人知道为什么吗?

(如果您想了解所有背景色的东西,我使用了一个jQuery插件,但没有添加到此片段中)



var intervalID;
$('.gal').click(function() {
  var photoID = jQuery(this).attr("id");
  alert(alerts[photoID]);
});

var alerts = {
  //row one
  "1:1": "This animal is a penguin!",
  "1:2": "This animal is a lion!",
  "1:3": "This animal is a cat!",
  "1:4": "This animal is a giraffe!",
  //row two
  "2:1": "Cool looking ancient building!",
  "2:2": "Cool looking modern building!",
  "2:3": "Cool building from dubai!",
  "2:4": "Cool building by the water!"
};

$("#stop").click(function() {
  clearInterval(intervalID);
});

$(window).load(function() {
  animate();
});

function animate() {
  intervalID = setInterval(function() {
    var width = 25;
    $(".gal").animate({
      'marginLeft': '-=25px'
    });
    $(".gal").animate({
      'marginLeft': '+=25px'
    });
    $("#title").animate({
      'marginLeft': '+=' + width + 'px'
    }, "slow");
    $("#title").animate({
      'marginLeft': '-=' + width + 'px'
    }, "slow");
    $("body").animate({
      'backgroundColor': 'lightyellow'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'yellow'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'orange'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'red'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'lightpink'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'pink'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'purple'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'blue'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'lightblue'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'cyan'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'green'
    }, 1000);
    $("body").animate({
      'backgroundColor': 'lightgreen'
    }, 1000);
  }, 0.1);
}

body {
  background-color: lightyellow;
}
#title {
  display: block;
  /*position:absolute;*/
}
.gal {
  display: block;
  margin: 20px;
  width: 250px;
  height: 200px;
  border: 5px solid black;
}
#stop {
  position: fixed;
  bottom: 0;
  right: 0;
  border: 3px solid red;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <title>JS Functions</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
  <div class="container-fluid">
    <button id="stop" class="btn-warning">Stop This Madness!</button>
    <h1 id="title" style="margin-left: 20px;" class="text-primary">Image Gallery:</h1>
    <div class="row">
      <div class="col-md-3">
        <img id="1:1" src="http://ngm.nationalgeographic.com/2012/11/emperor-penguins/img/02-airborne-penguin-exits-water_1600.jpg" class="gal">
      </div>
      <div class="col-md-3">
        <img id="1:2" src="http://efdreams.com/data_images/dreams/lion/lion-03.jpg" class="gal">
      </div>
      <div class="col-md-3">
        <img id="1:3" src="https://s3.graphiq.com/sites/default/files/stories/t2/tiny_cat_12573_8950.jpg" class="gal" />
      </div>
      <div class="col-md-3">
        <img id="1:4" src="https://upload.wikimedia.org/wikipedia/commons/0/02/Giraffe_Ithala_KZN_South_Africa_Luca_Galuzzi_2004.JPG" class="gal">
      </div>
    </div>
    <div class="row">
      <div class="col-md-3">
        <img id="2:1" src="http://cdn.mos.cms.futurecdn.net/78b7453e70727aae7eed989ff2cee83d.jpg" class="gal" />
      </div>
      <div class="col-md-3">
        <img id="2:2" src="http://thegrumpyoldlimey.com/images/buildings/dome_feature.jpg" class="gal" />
      </div>
      <div class="col-md-3">
        <img id="2:3" src="https://d3dupjkkwlat3o.cloudfront.net/399433011453/2071971/576xN?1410992818" class="gal" />
      </div>
      <div class="col-md-3">
        <img id="2:4" src="http://www.jazzhostels.com/blog/wp-content/uploads/2014/09/hemispheric-photo-valencia-spain-cc.jpg" class="gal">
      </div>
    </div>
  </div>
  <script></script>
  <script src="script.js"></script>
</body>

</html>

最佳答案

您需要了解两个基本要点:


setInterval()的延迟以毫秒为单位,并且您已指定0.1的延迟-这意味着您已尝试将函数调度为每秒运行10000次。在实践中,JS不允许您进入5ms以下:指定的任何较短的延迟都将被四舍五入,但这仍然意味着您的函数每秒将运行约200次。
当您在同一个元素上多次调用.animate()时,就像对.gal#titlebody所做的那样,它将使其他动画排队,这些动画将在当前动画结束后运行。


将这两个点放在一起,您的代码每5ms会将多个动画添加到队列中,每个动画花费的时间比5ms长得多。因此,即使您调用clearInterval(),也已经有大量动画在排队,它们将需要很长时间才能完成。

您可以使用.stop()方法停止当前正在进行的动画并清除给定元素的动画队列:

$(".gal").stop(true);


但是尝试使用setInterval()管理正在进行的动画总是有些笨拙,尤其是在您指定了多个具有不同时间的动画的情况下。但是幸运的是,.animate()方法使您可以提供一个在动画完成后运行的回调函数,因此您可以从那里安排其他处理。

您在评论中询问是否存在一种更有效的动画管理方法:对于所有这些颜色更改,我建议使用数组,然后在当前颜色更改完成后再次调用.animate()以获取数组中的下一个颜色。

所以也许像下面这样,请注意,为了使这个答案更短,我删除了一些与动画无关的代码,并且将动画代码分成三个函数以使其更清晰对你来说每个人在做什么:



$("#stop").click(function() {
  $(".gal, #title, body").stop(true);
});

$(window).load(function() {
  animateGallery();
  animateTitle();
  animateBody();
});

function animateGallery() {
  $(".gal").animate({
    'marginLeft': '-=25px'
  }, "slow").animate({
    'marginLeft': '+=25px'
  }, "slow", animateGallery); // note the function set as final argument
                              // - it will be called when animation finishes
}

function animateTitle() {
  var width = 25;
  $("#title").animate({
    'marginLeft': '+=' + width + 'px'
  }, "slow").animate({
    'marginLeft': '-=' + width + 'px'
  }, "slow", animateTitle); // note the function set as final argument
}

var colors = ['lightyellow', 'yellow', 'orange', 'red', 'lightpink', 'pink', 'purple', 'blue', 'lightblue', 'cyan', 'green', 'lightgreen'];
var currentColor = 0;

function animateBody() {
  $("body").animate({
    'backgroundColor': colors[currentColor]
  }, 1000, animateBody); // note the function set as final argument
  currentColor = (currentColor + 1) % colors.length;
}

#title { display: block; }
.gal { display: block; margin: 20px; width: 250px; height: 200px; border: 5px solid black; }
#stop { position: fixed; z-index: 100; bottom: 0; right: 0; border: 3px solid red; }

<!DOCTYPE html>
<html lang="en">
<head>
  <title>JS Functions</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
</head>
<body>
  <div class="container-fluid">
    <button id="stop" class="btn-warning">Stop This Madness!</button>
    <h1 id="title" style="margin-left: 20px;" class="text-primary">Image Gallery:</h1>
    <div class="row">
      <div class="col-md-3">
        <img id="2:1" src="http://cdn.mos.cms.futurecdn.net/78b7453e70727aae7eed989ff2cee83d.jpg" class="gal" />
      </div>
      <div class="col-md-3">
        <img id="2:2" src="http://thegrumpyoldlimey.com/images/buildings/dome_feature.jpg" class="gal" />
      </div>
      <div class="col-md-3">
        <img id="2:3" src="https://d3dupjkkwlat3o.cloudfront.net/399433011453/2071971/576xN?1410992818" class="gal" />
      </div>
      <div class="col-md-3">
        <img id="2:4" src="http://www.jazzhostels.com/blog/wp-content/uploads/2014/09/hemispheric-photo-valencia-spain-cc.jpg" class="gal">
      </div>
    </div>
  </div>
</body>
</html>

10-01 01:45