使用jquery滑动元素

时间:2015-09-01 08:34:29

标签: javascript jquery css

我试图在我的网站上播放一些内容,我尝试运行此代码,但滑动仅在第一次点击时发生,无法找到原因。这是我的代码片段: Html:



$("#go").click(function() {
  $(".block").animate({
    right: 85
  }, {
    duration: 800,
    step: function(now, fx) {
      $(".block:gt(0)").css("right", now);
    }
  });
});

div {
  position: relative;
  background-color: #abc;
  width: 70px;
  height: 70px;
  float: left;
  margin: 5px;
}

<p>
  <button id="go">Run »</button>
</p>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

关键是'+=85'

$("#go").click(function() {
  $(".block").animate({
    right: '+=85'
  }, {
    duration: 800,
    step: function(now, fx) {
      $(".block:gt(0)").css("right", now);
    }
  });
});
div {
  position: relative;
  background-color: #abc;
  width: 70px;
  height: 70px;
  float: left;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>
  <button id="go">Run »</button>
</p>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>

顺便说一句,我不知道这里step函数到底有什么用途。

答案 1 :(得分:0)

您只需将+=添加到号码检查代码段即可。因此,在每次点击时,它会向右{85}像素加+=表示{right = right + 85},或者您也可以使用-= {right = right - 85}作为negetive accumulators

参考:http://api.jquery.com/animate/

&#13;
&#13;
$("#go").click(function() {
  $(".block").animate({
    right: '+=85'
  }, {
    duration: 800,
    step: function(now, fx) {
      $(".block:gt(0)").css("right", now);
    }
  });
});
&#13;
div {
  position: relative;
  background-color: #abc;
  width: 70px;
  height: 70px;
  float: left;
  margin: 5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <button id="go">Run »</button>
</p>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
&#13;
&#13;
&#13;