如何交换所有div元素的位置

3
这是我的图库样式: images gallery 我需要javascript/jquery函数:“arrow_left()”和“arrow_right()”,用于更改带有图像的div的位置(所有内容都位于中间的div)。例如,当我在“image 2”上单击右箭头时,其应与“image 3”交换位置。 下面是如何交换“image 2”和“image 3”的示例,使“image 2”为空(“image 3”将被删除)。
<script>
    function arrow_right(id_number) {
        var present_div = $('#' + id_number);
        id_number = id_number + 1;
        var next_div = $('#' + id_number);

        $(present_div).replaceWith(next_div); 
        //$(next_div).replaceWith(present_div); <- doesn't work
    }

    function arrow_left(id_number) {
        var present_div = $('#' + id_number);
        id_number = id_number - 1;
        var prev_div = $('#' + id_number);

        $(present_div).replaceWith(prev_div); 
        //$(prev_div).replaceWith(present_div); <- doesn't work
    }
</script>

    <div id='ID_1' class='col-lg-4 col-md-6 portfolio-item'>
    <div class='thumbnail'>
        <div onclick='arrow_left(1);'><span class='glyphicon glyphicon-arrow-left' style='color: yellow; left: 78px; top: 5px;'></span></div>
        <div onclick='arrow_right(1);'><span class='glyphicon glyphicon-arrow-right' style='color: yellow; left: 136px; top: 5px;'></span></div>
        <img id='1' class='img-responsive' src='path/to/img'> 
    </div>
</div>
<div id='ID_2' class='col-lg-4 col-md-6 portfolio-item'>
    <div class='thumbnail'>
        <div onclick='arrow_left(2);'><span class='glyphicon glyphicon-arrow-left' style='color: yellow; left: 78px; top: 5px;'></span></div>
        <div onclick='arrow_right(2);'><span class='glyphicon glyphicon-arrow-right' style='color: yellow; left: 136px; top: 5px;'></span></div>
        <img id='2' class='img-responsive' src='path/to/img'> 
    </div>
</div>

<div class='clearfix visible-md-block'></div>

<div id='ID_3' class='col-lg-4 col-md-6 portfolio-item'>
    <div class='thumbnail'>
        <div onclick='arrow_left(3);'><span class='glyphicon glyphicon-arrow-left' style='color: yellow; left: 78px; top: 5px;'></span></div>
        <div onclick='arrow_right(3);'><span class='glyphicon glyphicon-arrow-right' style='color: yellow; left: 136px; top: 5px;'></span></div>
        <img id='3' class='img-responsive' src='path/to/img'> 
    </div>
</div>
<div class='clearfix visible-lg-block'></div>
<div id='ID_4' class='col-lg-4 col-md-6 portfolio-item'>
    <div class='thumbnail'>
        <div onclick='arrow_left(4);'><span class='glyphicon glyphicon-arrow-left' style='color: yellow; left: 78px; top: 5px;'></span></div>
        <div onclick='arrow_right(4);'><span class='glyphicon glyphicon-arrow-right' style='color: yellow; left: 136px; top: 5px;'></span></div>
        <img id='4' class='img-responsive' src='path/to/img'> 
    </div>
</div>

<div class='clearfix visible-md-block'></div>

<div id='ID_5' class='col-lg-4 col-md-6 portfolio-item'>
    <div class='thumbnail'>
        <div onclick='arrow_left(5);'><span class='glyphicon glyphicon-arrow-left' style='color: yellow; left: 78px; top: 5px;'></span></div>
        <div onclick='arrow_right(5);'><span class='glyphicon glyphicon-arrow-right' style='color: yellow; left: 136px; top: 5px;'></span></div>
        <img id='5' class='img-responsive' src='path/to/img'> 
    </div>
</div>
<div id='ID_6' class='col-lg-4 col-md-6 portfolio-item'>
    <div class='thumbnail'>
        <div onclick='arrow_left(6);'><span class='glyphicon glyphicon-arrow-left' style='color: yellow; left: 78px; top: 5px;'></span></div>
        <div onclick='arrow_right(6);'><span class='glyphicon glyphicon-arrow-right' style='color: yellow; left: 136px; top: 5px;'></span></div>
        <img id='6' class='img-responsive' src='path/to/img'> 
    </div>
</div>
<div class='clearfix visible-lg-block'></div>

<div class='clearfix visible-md-block'></div>

<div id='ID_7' class='col-lg-4 col-md-6 portfolio-item'>
    <div class='thumbnail'>
        <div onclick='arrow_left(7);'><span class='glyphicon glyphicon-arrow-left' style='color: yellow; left: 78px; top: 5px;'></span></div>
        <div onclick='arrow_right(7);'><span class='glyphicon glyphicon-arrow-right' style='color: yellow; left: 136px; top: 5px;'></span></div>
        <img id='7' class='img-responsive' src='path/to/img'> 
    </div>
</div>

我不知道如何升级它。如果有人能帮我吗?也许有人知道其他解决方案,但不要拖放 - 我测试了jQuery UI sortable,效果不好。

我不需要滑块。我需要在页面中呈现所有图像并更改它们的顺序(在管理员面板中)。数据库中每个图像都有一个“Order”字段,它影响图像在页面上的显示顺序。我正在寻找一个很好的解决方案来更改这个顺序。


这是在重复造轮子,已经有数百个教程和解决方案可以完全满足您的需求甚至更多。只需要谷歌一下即可。 - user2521387
你能给些例子吗?我找不到类似的东西。 - Konrad
一个谷歌搜索,第一条结果 - 第一行 http://www.menucool.com/slider/javascript-image-slider-demo4 关键词是:带有按钮的图像旋转器 - user2521387
不好意思,你误解了我的意思。我不需要滑块。我需要在页面上展示所有的图片,并且可以通过管理员面板改变它们的顺序。数据库中每张图片都有一个“顺序”字段,它会影响图片在页面上的显示顺序。我正在寻找一种优雅的方法来改变这个顺序。 - Konrad
4个回答

1
你可以像这样替换元素的outerHTML:
 function arrow_change(el, fw) {
    var id = el.parentElement.parentElement.id;
    var id_number = eval(id.substr(3))
    var present_div = $('#ID_' + id_number + " div").get(0);//get(0) returns first DOM Element
    id_number = id_number + fw //fw is either 1 or -1;
    var next_div = $('#ID_' + id_number + " div").get(0);
    var present_html = present_div.outerHTML;
    var next_html = next_div.outerHTML;
    present_div.outerHTML = next_html;
    next_div.outerHTML = present_html;   
}

在参数中指定elthis,并将fw设置为1-1,具体取决于向右还是向左。

例如:onclick="arrow_change(this, 1)"表示向右移动。

Demo: https://codecanister.com/Project/d547eed9/1/fullscreen/b


谢谢,但我需要切换整个div,还有其他东西我也需要移动。 - Konrad
现在它可以工作了,谢谢!但是它只能使用两个图像。也许应该保留带有id='ID_X'的div,并且我们应该仅交换父div(具有class='thumbnail')。你有想法如何做到这一点吗? - Konrad
我现在有一个可行的答案,使用元素的id来交换。 - jlynch630
谢谢您的时间!我非常感激您的帮助。它有效了! - Konrad

0

这里有一个交换卡片/网格项的示例。我使用了你发布的HTML的简化版本。从你使用的样式来看,我假设你正在使用Bootstrap,并在演示中包含了它。如果你想要一个不基于Bootstrap/jQuery的版本,请告诉我,我很乐意更新这个。

由于我使用的图像占位符服务通常会为给定大小返回相同的图像,因此我在卡片标题中包含了一个静态数字,以便您可以看到交换。

我建议不要通过更新属性或其他“文本”方法进行交换,因为如果您拥有事件处理程序(例如点击跟踪)的卡片,那么您将很难维护它们。

这种方法也不需要维护当前、下一个和上一个的概念,因为新的点击处理程序可以轻松地为您解决这个问题。

我添加了一些额外的CSS来“隐藏”没有任何作用的箭头。你也可以这样做或者删除那些样式元素。即使这些元素仍然存在,代码仍然可以正确运行。

这里还有一些类似的问题,你可能也会感兴趣:

function swapChildren($parentA, $parentB) {
  if ($parentA.length === 0 || $parentB.length === 0){ return; }

  var $childrenA = $parentA.children();
  var $childrenB = $parentB.children();

  $parentA.append($childrenB);
  $parentB.append($childrenA);
}

$(".arrowLeft").on("click", function(){
  var $parent = $(this).closest(".portfolio-item");
  swapChildren($parent, $parent.prev());
});

$(".arrowRight").on("click", function(){
  var $parent = $(this).closest(".portfolio-item");
  swapChildren($parent, $parent.next());
});
.portfolio-item .thumbnail { text-align: center; }
.portfolio-item .thumbnail > div { display: inline-block; padding: 0.5em; }
.glyphicon { font-size: 2em; color: red; }

/*  hide arrows that don't do anything */
.row .portfolio-item:first-child .arrowLeft { display: none; }
.row .portfolio-item:last-child .arrowRight { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">

<div class="container">
  <div class="row">

    <div class='col-xs-4 portfolio-item'>
      <div class='thumbnail'>
        <div class="arrowLeft"><span class='glyphicon glyphicon-arrow-left'></span></div>
        <span style="font-size: 2em;"> 1 </span>
        <div class="arrowRight"><span class='glyphicon glyphicon-arrow-right'></span></div>
        <img id='1' class='img-responsive' src='http://lorempixel.com/200/100/'>
      </div>
    </div>

    <div class='col-xs-4 portfolio-item'>
      <div class='thumbnail'>
        <div class="arrowLeft"><span class='glyphicon glyphicon-arrow-left'></span></div>
        <span style="font-size: 2em;"> 2 </span>
        <div class="arrowRight"><span class='glyphicon glyphicon-arrow-right'></span></div>
        <img id='1' class='img-responsive' src='http://lorempixel.com/200/100/'>
      </div>
    </div>

    <div class='col-xs-4 portfolio-item'>
      <div class='thumbnail'>
        <div class="arrowLeft"><span class='glyphicon glyphicon-arrow-left'></span></div>
        <span style="font-size: 2em;"> 3 </span>
        <div class="arrowRight"><span class='glyphicon glyphicon-arrow-right'></span></div>
        <img id='1' class='img-responsive' src='http://lorempixel.com/200/100/'>
      </div>
    </div>

    <div class='col-xs-4 portfolio-item'>
      <div class='thumbnail'>
        <div class="arrowLeft"><span class='glyphicon glyphicon-arrow-left'></span></div>
        <span style="font-size: 2em;"> 4 </span>
        <div class="arrowRight"><span class='glyphicon glyphicon-arrow-right'></span></div>
        <img id='1' class='img-responsive' src='http://lorempixel.com/200/100/'>
      </div>
    </div>

    <div class='col-xs-4 portfolio-item'>
      <div class='thumbnail'>
        <div class="arrowLeft"><span class='glyphicon glyphicon-arrow-left'></span></div>
        <span style="font-size: 2em;"> 5 </span>
        <div class="arrowRight"><span class='glyphicon glyphicon-arrow-right'></span></div>
        <img id='1' class='img-responsive' src='http://lorempixel.com/200/100/'>
      </div>
    </div>

  </div>
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>


1
谢谢您的时间!我非常感激您的帮助。 - Konrad

0
这里有一个可能的解决方案,可以使用普通的 JavaScript 处理任意数量的图像:

// Count Number of Images
var figures = document.getElementsByTagName('figure');


// Add Buttons to each Image
for (var i = 0; i < figures.length; i++) {

    // Create Move Image Left Button
    var leftSpan = document.createElement('span');
    leftSpan.classList.add('left');
    var leftArrow = document.createTextNode('\u25c0');
    leftSpan.appendChild(leftArrow);

    // Create Move Image Right Button
    var rightSpan = document.createElement('span');
    rightSpan.classList.add('right');
    var rightArrow = document.createTextNode('\u25b6');
    rightSpan.appendChild(rightArrow);

    // Add Left and Right Buttons to each Image
    figures[i].appendChild(leftSpan);
    figures[i].appendChild(rightSpan);
}


// moveLeft Function

function moveLeft() {
    for (var i = 0; i < figures.length; i++) {
        if (figures[i] === this.parentNode) {
            var thisFigure = this.parentNode;
            var currentImage = thisFigure.getElementsByTagName('img')[0];
            var currentFigcaption = thisFigure.getElementsByTagName('figcaption')[0];

            var previousFigure = figures[(i-1)];
            var previousImage = previousFigure.getElementsByTagName('img')[0];
            var previousFigcaption = previousFigure.getElementsByTagName('figcaption')[0];

            thisFigure.insertBefore(previousFigcaption,currentFigcaption);
            previousFigure.insertBefore(currentFigcaption,previousImage);
            thisFigure.insertBefore(previousImage,currentImage);
            previousFigure.insertBefore(currentImage,currentFigcaption);
        }
    }
}


// moveRight Function

function moveRight() {
    for (var i = 0; i < figures.length; i++) {
        if (figures[i] === this.parentNode) {
            var thisFigure = this.parentNode;
            var currentImage = thisFigure.getElementsByTagName('img')[0];
            var currentFigcaption = thisFigure.getElementsByTagName('figcaption')[0];

            var nextFigure = figures[(i+1)];
            var nextImage = nextFigure.getElementsByTagName('img')[0];
            var nextFigcaption = nextFigure.getElementsByTagName('figcaption')[0];

            thisFigure.insertBefore(nextFigcaption,currentFigcaption);
            nextFigure.insertBefore(currentFigcaption,nextImage);
            thisFigure.insertBefore(nextImage,currentImage);
            nextFigure.insertBefore(currentImage,currentFigcaption);
        }
    }
}


// Initialise Buttons
for (var i = 0; i < figures.length; i++) {

    if (i > 0) {
        var leftButton = figures[i].getElementsByClassName('left')[0];
        leftButton.addEventListener('click',moveLeft,false);
    }

    if (i < (figures.length - 1)) {
        var rightButton = figures[i].getElementsByClassName('right')[0];
        rightButton.addEventListener('click',moveRight,false);
    }
}
figure {
display: block;
position: relative;
float: left;
margin: 12px;
width: 200px;
height: 124px;
border: 3px solid rgb(0,0,0);
}

figure img {
display: block;
width: 176px;
height: 76px;
margin: 12px 12px 6px;
border: 1px solid rgb(31,31,31);
}

figcaption {
text-align: center;
}

.left {
display: block;
position: absolute;
left: 0;
bottom: 0;
cursor: pointer;
}

.right {
display: block;
position: absolute;
right: 0;
bottom: 0;
cursor: pointer;
}
<figure>
<img src="/image1.png" title="Image 1" alt="Image 1" />
<figcaption>Image 1</figcaption>
</figure>

<figure>
<img src="/image2.png" title="Image 2" alt="Image 2" />
<figcaption>Image 2</figcaption>
</figure>

<figure>
<img src="/image3.png" title="Image 3" alt="Image 3" />
<figcaption>Image 3</figcaption>
</figure>


1
谢谢您的时间!我非常感激您的帮助。 - Konrad

0
第二张图片没有被更新的原因是您使用了replaceWith。您可以将其更改为{{link1:html()}}等方式。 您还可以通过添加第二个参数来改进您的函数,以计算id,因为arrow_left和arrow_right之间唯一的区别是加1或减1。
function swapImage(shouldAddOne) {
  var id = $(event.target).parents('.portfolio-item').first().attr('id');
  id = id.split('_');
  id = id[id.length-1];
  id = parseInt(id, 10);
  var present_div = $('#ID_' + id)
  var present_div_html = present_div.html();
  id = shouldAddOne ? id + 1 : id - 1;
  var next_div = $('#ID_' + id);
  var next_div_html = next_div.html();

  $(present_div).html(next_div_html); 
  $(next_div).html(present_div_html);
}

你可以在 HTML 中这样使用它:swapImage(true) 向右移动,swapImage(false) 向左移动

如果你更喜欢使用库,可以看看 这个幻灯片


嗯...我看它应该可以工作,但它什么也没做... :/ - Konrad
当我使用alert(next_div_html)或alert(present_div_html)时,会得到一个空的提示。 - Konrad
顺便说一下,我不需要滑块。我需要在页面上呈现所有图片并更改它们的顺序(在管理员面板中)。数据库中的每个图像都有一个“顺序”字段,它影响图像在页面上的显示顺序。我正在寻找一个不错的解决方案来更改此顺序。 - Konrad
现在它可以工作了,谢谢!我怎么没注意到缺少 'ID_'。但是它只能使用两个图像。也许应该保留带有id ='ID_X'的div,并且我们应该仅交换父div(具有class ='thumbnail')。你有想法如何做吗? - Konrad
谢谢您的时间!我非常感激您的帮助。 - Konrad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接