簡體   English   中英

從最高div的位置交換div的位置

[英]swap div's position from top div's

我正在嘗試從頂部交換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本身做到這一點?

我建議使用CSS定位頂部div並按如下所示交換類:

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

這將使您單擊的任何內容都與第一個元素交換。

$(".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());
  }
});

如果您只想將clicked元素移至頂部,則只需

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

要使用jQuery交換兩個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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM