如何使用jquery和javascript使每次点击的标题加速

时间:2016-03-24 13:16:54

标签: javascript jquery

我试图将它发送到每次点击它加速的标题的地方。然而,它要么加速前几次点击,要么开始变得非常慢。我也尝试将* = 999的符号更改为+ =和 - =并且我没有找到任何不同的结果。请帮忙。



var x = 10000
  //x is the speed of animate
  //this is where the movement is defined for the heading
function move() {
    $("h1").animate({
      "left": "+=200px"
    }, x).animate({
      "top": "+=200px"
    }, x).animate({
      "left": "-=200px"
    }, x).animate({
      "top": "-=200px"
    }, x);
  }
  //this should make the heading move faster
$("h1").click(function() {
  move()
    //this should make it move faster
  x *= 999
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1 id="heading" style="position:absolute;">Watch the moving heading!</h1>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

首先,您的x告诉您动画需要多长时间才能完成。因此10000表示end after 10s90000表示end in 90s - 更大意味着更慢。

而不是增加时间(*=+=++),您需要减少时间(/=-=--

我还添加了.finish()来完成当前动画并开始播放,如果愿意,可以将其删除。

&#13;
&#13;
var x = 10000;

function move() {
    $("h1").finish().animate({
      "left": "+=200px"
    }, x).animate({
      "top": "+=200px"
    }, x).animate({
      "left": "-=200px"
    }, x).animate({
      "top": "-=200px"
    }, x);
  }

$("h1").click(function() {
  move();
  x -= 500;
  x = Math.max(1, x);
  console.log(x);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1 id="heading" style="position:absolute;">Watch the moving heading!</h1>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

值得注意的事情。

1)要提高动画的速度,您必须减少动画所需的时间。所以你需要x -= 300;而不是这样做x *= 999

2)完成关闭现有动画并在点击h1时启动新动画。使用.finish()完成正在运行的动画。

3)从左侧移开200像素,然后从顶部移开200像素,现在您必须移回原始位置,而不是从原始位置移动-200,您必须使用{{ 1}}和left:0px移回初始位置。

检查工作演示。

&#13;
&#13;
top:0px
&#13;
var x = 1000

  //x is the speed of animate
  //this is where the movement is defined for the heading
function move() {
   
    $("h1").finish().animate({
      "left": "200px"
    }, x).animate({
      "top": "200px"
    }, x).animate({
      "left": "0px"
    }, x).animate({
      "top": "0px"
    }, x);
  }
  //this should make the heading move faster
$("h1").click(function() {
  move();
    //this should make it move faster
    if(x > 100) x -= 300;
});
&#13;
&#13;
&#13;