[英]Swap div's position at certain index
我試圖從頂部開始交換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的
var objectDivs = $('.wrap');
objectDivs.on('click', function() {
var $this = $(this);
objectDivs.eq(0).html($this);
$this.remove();
})
事實是我不想刪除我點擊的div而不想交換周圍的位置。
我怎么能用jQuery本身做到這一點?
$(".wrap").on("click", function(){ $(this).parent().prepend(this); });
.wrap{background:#eee;padding:10px; margin:10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrapper"> <div class="wrap">1</div> <div class="wrap">2</div> <div class="wrap">3</div> </div>
您應該嘗試使用insertBefore和insertAfter。 例如: -
(function($) { $(".wrap").on("click", function() { if ($(this).index() == 0) { $(this).insertAfter($(this).next()); } else { $(this).insertBefore($(this).prev()); } }); }(jQuery));
.wrap { width: 50px; height: 50px; } .wrap1 { background: red; } .wrap2 { background: yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div class="wrapper"> <div class="wrap wrap1"></div> <div class="wrap wrap2"></div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.