If I have the HTML:
如果我有HTML:
<div id="divOne">Hello</div> <div id="divTwo">World</div>
Is it possible with CSS/JS/jQuery to swap it around so the contents of divTwo
appears in the position of divOne
and vice-versa ? I'm just looking to change the position of each div, so I don't want any solution that involves setting/swapping the HTML of each.
有没有可能用CSS/JS/jQuery来交换,让div2的内容出现在divOne的位置,反之亦然?我只是想改变每个div的位置,所以我不想要任何涉及设置/交换每个div的HTML的解决方案。
The idea is to let a user customise the order content appears on the page. Is what I'm trying to do a good way of going about that, or is there a better way of achieving it ?
其目的是让用户自定义订单内容出现在页面上。我想做的是一种很好的方式去实现它,还是有更好的方式去实现它?
3 个解决方案
#1
8
You'll be relieved to know it's not hard at all using jQuery.
知道使用jQuery一点都不难,你就放心了。
$("#divOne").before($("#divTwo"));
Edit: If you're talking about implementing drag-and-drop functionality for ordering the divs, take a look at jQuery UI's sortable plugin... http://jqueryui.com/demos/sortable/
编辑:如果您正在讨论实现用于订购div的拖放功能,请查看jQuery UI的可排序插件……http://jqueryui.com/demos/sortable/
#2
2
Perhaps by using floats.
也许使用浮动。
#divOne {
float: right;
}
#divTwo {
float: left;
}
YMMV.
YMMV。
#3
1
http://snipplr.com/view/50142/swap-child-nodes/ has the code to swap 2 elements with each other.
http://snipplr.com/view/50142/swap-child-nodes/具有相互交换两个元素的代码。
I have also modified the same code so that it also preserves event listeners (addEventListener
) in the elements that are being swapped and their child nodes.
我还修改了相同的代码,以便在交换的元素及其子节点中保存事件监听器(addEventListener)。
function swapNodes(node1, node2) {
node2_copy = node2.cloneNode(true);
node1.parentNode.insertBefore(node2_copy, node1);
node2.parentNode.insertBefore(node1, node2);
node2.parentNode.replaceChild(node2, node2_copy);
}
#1
8
You'll be relieved to know it's not hard at all using jQuery.
知道使用jQuery一点都不难,你就放心了。
$("#divOne").before($("#divTwo"));
Edit: If you're talking about implementing drag-and-drop functionality for ordering the divs, take a look at jQuery UI's sortable plugin... http://jqueryui.com/demos/sortable/
编辑:如果您正在讨论实现用于订购div的拖放功能,请查看jQuery UI的可排序插件……http://jqueryui.com/demos/sortable/
#2
2
Perhaps by using floats.
也许使用浮动。
#divOne {
float: right;
}
#divTwo {
float: left;
}
YMMV.
YMMV。
#3
1
http://snipplr.com/view/50142/swap-child-nodes/ has the code to swap 2 elements with each other.
http://snipplr.com/view/50142/swap-child-nodes/具有相互交换两个元素的代码。
I have also modified the same code so that it also preserves event listeners (addEventListener
) in the elements that are being swapped and their child nodes.
我还修改了相同的代码,以便在交换的元素及其子节点中保存事件监听器(addEventListener)。
function swapNodes(node1, node2) {
node2_copy = node2.cloneNode(true);
node1.parentNode.insertBefore(node2_copy, node1);
node2.parentNode.insertBefore(node1, node2);
node2.parentNode.replaceChild(node2, node2_copy);
}