【问题标题】:Animate the div left and right using css margins in jquery使用 jquery 中的 css 边距为 div 左右设置动画
【发布时间】:2020-11-10 09:41:53
【问题描述】:

第一次点击按钮时,div 应该向右移动 300 像素。在按钮 div 上单击第二次时,动画应向左 300 像素。下次点击也一样。

我尝试过,但它只向左移动,但我如何切换以将 div 再次向右移动?

代码-

<script>
        $(document).ready(function(){
            $("button").click(function(){
                $("div").animate({ marginLeft: "300px"});
            });
        });
 </script>

<style>
    button{
        color:white;
        background-color: red;
        padding: 10px 20px;
    }
    div{
        display: inline-block;
        width: 150px;
        height: 150px;
        background-color: yellow;
        margin: 20px 50px;
    }
</style>

HTML -

<button>Click me</button>
<div>Hello</div>

【问题讨论】:

    标签: html jquery css


    【解决方案1】:

    要实现这一点,请使用toggleClass() 而不是animate() 在连续单击时添加/删除类。然后你可以在 CSS 中使用transition 来控制动画,这比 JS 的表现要好得多。试试这个:

    jQuery($ => {
      $("button").click(function() {
        $("div").toggleClass('right');
      });
    });
    button {
      color: white;
      background-color: red;
      padding: 10px 20px;
    }
    
    div {
      display: inline-block;
      width: 150px;
      height: 150px;
      background-color: yellow;
      margin: 20px 50px;
      transition: margin-left 300ms;
    }
    
    div.right {
      margin-left: 300px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>Click me</button>
    <div>Hello</div>

    我特别想使用 Jquery Animation 来实现解决方案。我们可以使用Jquery动画获得解决方案吗

    在这种情况下,您需要检查当前边距是多少,并在此基础上设置新值。但是您应该注意,到目前为止,上述 CSS 方法是更好的做法。

    jQuery($ => {
      $("button").click(function() {
        let margin = $('div').css('margin-left') == '50px' ? '300px' : '50px';
        $("div").animate({'margin-left': margin});
      });
    });
    button {
      color: white;
      background-color: red;
      padding: 10px 20px;
    }
    
    div {
      display: inline-block;
      width: 150px;
      height: 150px;
      background-color: yellow;
      margin: 20px 50px;
      transition: margin-left 300ms;
    }
    
    div.right {
      margin-left: 300px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>Click me</button>
    <div>Hello</div>

    【讨论】:

    • 我特别想使用 Jquery Animation 来实现解决方案。我们可以使用 Jquery 动画@Rory McCrossan 获得解决方案吗?
    • 请注意,Element.animate() 函数是 vanilla JS,而不是 jQuery。
    • @OskarGrosser 好吧,also 有一个原生的animate() 方法,但这显然是使用jQuery 的:api.jquery.com/animate
    • 我的错,我不知何故认为$() 返回一个普通的Element-object,而不是jQuery-object。你是绝对正确的。但在这种情况下,Element.animate()jQuery.animate() 函数的工作方式完全相同。
    猜你喜欢
    • 2011-03-03
    • 2015-06-29
    • 1970-01-01
    • 2011-03-04
    • 2013-10-31
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多