【问题标题】:Re-ordering div positions with jQuery?用jQuery重新排序div位置?
【发布时间】:2011-10-10 22:49:22
【问题描述】:

我正在尝试模仿本网站上的赞成票反对票系统。有没有一种简单的方法可以在 jquery 中移动 div 的位置(带动画)?

假设我有以下物品:

<div id="items">
  <div id="item1">item 1</div>
  <div id="item2">item 2</div>
  <div id="item3">item 3</div>
</div>

我希望能够调用一个函数,将项目 3 平滑地移动到一个位置:

<div id="items">
  <div id="item1">item 1</div>
  <div id="item3">item 3</div>
  <div id="item2">item 2</div>
</div>

在 jQuery 中有没有简单的方法来做到这一点?

【问题讨论】:

    标签: jquery html jquery-animate


    【解决方案1】:

    可能是这样的:

    $('.move-up').click(function(e){
        var $div = $(this).closest('div');
    
        // Does the element have anywhere to move?
        if ($div.index() > 0){
            $div.fadeOut('slow',function(){
                $div.insertBefore($div.prev('div')).fadeIn('slow');
            });
        }
    });
    
    $('.move-down').click(function(e){
        var $div = $(this).closest('div');
    
        // Does the element have anywhere to move?
        if ($div.index() <= ($div.siblings('div').length - 1)){
            $div.fadeOut('slow',function(){
                $div.insertAfter($div.next('div')).fadeIn('slow');
            });
        }
    });
    

    Demo

    基本上:

    1. 抓住要移动的元素 ($div)
    2. 淡出(使用fadeOut() 提供漂亮的 UI 效果)
    3. 将其移动到上一个/下一个项目之前或之后(使用insertBefore()insertAfter()
    4. 重新淡入(fadeIn() 的另一个 UI 效果)

    【讨论】:

      【解决方案2】:

      是的,可以通过更改其 css 样式来实现。修改它的位置http://api.jquery.com/position/也可以试试这个How to position one element relative to another with jQuery?

      【讨论】:

      • 如果您使用 :odd 之类的东西为行着色,这将无济于事。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多