jQuery动画仅起作用一次

9

我正在尝试使用jquery的简单动画功能。在我的应用程序中,我有两个按钮“向右滑动”和“向左滑动”。当我们点击这些按钮时,它们会将框向左或向右移动。我的向右移动按钮完美地工作,但是我的向左移动按钮只能工作一次。我的代码有什么问题?以下是我的代码:

$(document).ready(function() {

  $("#slideRightButton").click(function() {
    $("#boxToBeMoved").animate({
      left: '+=10%'
    });
  });

  $("#slideLeftButton").click(function() {
    $("#boxToBeMoved").animate({
      right: '+=10%'
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button id="slideRightButton">Slide Right</button>
<button id="slideLeftButton">Slide Left</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div id="boxToBeMoved" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

上面的代码只是 W3Schools 的 jQuery 教程的一个扩展,可以在这里找到:这里


你的意思是“但我的移动按钮只能工作一次”? - wibeasley
2个回答

9
你正在更改盒子的 leftright 属性,看起来 right 属性优先级更高并阻止了 left 属性的作用。
如果你让两个属性都采用相同的方式,一个加,一个减,那么它应该可以正常工作。
$("#slideRightButton").click(function(){
    $("div").animate({left: '+=10%'});
});
$("#slideLeftButton").click(function(){
    $("#boxToBeMoved").animate({left: '-=10%'});
});

有用的技巧!谢谢。 - user45437
如何防止网页超出100%后扩展? 如果超过100%,我不希望显示该框。 - user45437
@user45437 看一下我更新的答案。你需要为盒子设置一个包装器并给它一个宽度。 - ceferrari

5

更新包括作者要求不超过最大宽度。

为了实现这一目标,我包含了一个具有固定宽度的包装器div。

向右滑动时,它检查值是否大于父元素的宽度,如果是,则返回。

向左滑动也是如此,但如果值为负,它将返回,防止盒子滑动到父div的限制范围之外。

$(document).ready(function() {

  const slideVal = 30; // slide value (in pixels)

  $("#slideRightButton").click(function() {
    var box = $("#boxToBeMoved");
    if (parseInt(box.css("left")) + slideVal > parseInt(box.parent().width())) return;
    box.animate({
      left: '+=' + slideVal
    });
  });

  $("#slideLeftButton").click(function() {
    var box = $("#boxToBeMoved");
    if (parseInt(box.css("left")) - slideVal < 0) return;
    box.animate({
      left: '-=' + slideVal
    });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button id="slideRightButton">Slide Right</button>
<button id="slideLeftButton">Slide Left</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div id="wrapper" style="width: 200px">
  <div id="boxToBeMoved" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</div>


解释代码的工作原理将使答案更完美 :) - Not a bug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接