2016-04-14 15 views
0

divの位置を上からスワップしようとしています。別のdivをクリックするとスワップすることができます。トップdivのスワップdivの位置

HTML

<div class="wrap top"> 
    <input type="text" value="div1" class="textbox " /> 
</div> 
<div class="wrap"> 
    <input type="text" value="div2" class="textbox " /> 
</div> 
<div class="wrap"> 
    <input type="text" value="div3" class="textbox " /> 
</div> 

jQueryの

(function ($) { 
     $(".wrap").on("click", function() { 
      if ($(this).index() == 0) { 
      } else { 
       $(this).insertBefore($(this).prev()); 
      } 
     }); 
    }(jQuery)); 

事実は、私が代わりに周りの位置を入れ替えたい]をクリックしますdivを削除したくないです。

どうすればjQuery自身でこれを行うことができますか?

- :私はトップdivを配置するためにCSSを使用して、次のように単にクラスを入れ替えることをお勧め

+0

あなたが実際にコードマークアップを入れ替えるか、単に上部の要素のオーバーレイを作成する必要がありますかもう片方の? – Shakespeare

+0

removeClass( 'top')maybe – MeGoodGuy

+0

実際に私は1つの大きなdivと3つの別の小さなDivを持っています。大きなdivが上にあり、別の3つのdivが右側にあります。大きなdivは小さくて小さなdivが大きく表示されていることを示しています。 –

答えて

0

(function ($) { 
     $(".wrap").on("click", function() { 
      if ($(this).index() == 0) { 
      } else { 
       $(".wrap").removeClass("top"); 
       $(this).addClass("top"); 
      } 
     }); 
    }(jQuery)); 
-1

のjQueryを使用して、2つのDOM要素をスワップするには、このようなものを使用することができます

(function($) { 
 
    $(".wrap").on("click", function(event) { 
 
    var index = $(event.target).index(); 
 
    var first = $(".wrap").first(); 
 

 
    if (index > 0) { 
 
     $(first).swapWith(this); 
 
    } 
 
    }); 
 
}(jQuery)); 
 

 

 
jQuery.fn.swapWith = function(to) { 
 
    return this.each(function() { 
 
    var copy_to = $(to).clone(true); 
 
    var copy_from = $(this).clone(true); 
 
    $(to).replaceWith(copy_from); 
 
    $(this).replaceWith(copy_to); 
 
    }); 
 
};
.wrap { 
 
    height: 100px; 
 
    width: 200px; 
 
    margin: 10px 10px 10px 10px; 
 
    background-color: #2d8cd0; 
 
} 
 
h2 { 
 
    color: white; 
 
    text-align: center; 
 
    padding-top: 20px; 
 
    pointer-events: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 

 
<div class="wrap"> 
 
    <h2>1</h2> 
 
</div> 
 

 
<div class="wrap"> 
 
    <h2>2</h2> 
 
</div> 
 

 
<div class="wrap"> 
 
    <h2>3</h2> 
 
</div> 
 

 
<div class="wrap"> 
 
    <h2>4</h2> 
 
</div>

+0

これははるかに簡単に行うことができます。 first.insertBefore($(this)); $(this).prependTo($(this).parent()); –

0

これは、あなたが最初の要素をクリックしてください何でも交換します。

$(".wrap").on("click", function() { 
    var $this = $(this); 
    if ($this.index() == 0) { 
    } else { 
    var first = $this.siblings('.wrap').first(); 
    first.insertBefore($this); 
    $this.prependTo($this.parent()); 
    } 
}); 

あなただけの先頭にクリックされた要素を移動したい場合は、単に行うことができます

$this.prependTo($this.parent());