Ale*_*dre 21 html javascript css jquery
如何在不改变HTML源代码的情况下重新排序div?
例如,我希望div以#div2,#div1,#div3的顺序出现,但在HTML中它们是:
<div id="#div1"></div>
<div id="#div2"></div>
<div id="#div3"></div>
Run Code Online (Sandbox Code Playgroud)
谢谢!
Mag*_*nar 20
没有用css重新排序元素的方法.
您可以通过将它们全部浮动到右侧来水平反转它们的顺序.或者您可以相对于主体或其他包含元素绝对定位它们 - 但是对于元素的大小以及相对于页面上其他元素的定位存在严重限制.
简短回答:您只能在非常有限的情况下实现这一点.重新排序元素最好在标记中完成.
如果你无法控制html,你可以使用javascript.这里使用jQuery:
$("#div2").insertAfter("#div3");
$("#div1").prependTo("#div2");
Run Code Online (Sandbox Code Playgroud)
除非你的双手被束缚,否则我当然不建议这样做.它将更难维护,对于您的最终用户,它将使您的页面在设置页面时"晃动".
Jos*_*ola 12
我会使用Javascript相应地遍历节点.如果你想使用像jQuery这样的库,你可以使用上面的建议.如果您不想臃肿,请使用以下简单和简约的解决方案......
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function swapSibling(node1, node2) {
node1.parentNode.replaceChild(node1, node2);
node1.parentNode.insertBefore(node2, node1);
}
window.onload = function() {
swapSibling(document.getElementById('div1'), document.getElementById('div2'));
}
</script>
</head>
<body>
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
最好的祝福...
编辑:将函数名称从swapNode更改为swapSibling,因为我相当确定这只适用于具有相同父级的节点.
jon*_*ohn 10
在jQuery中,您可以执行以下操作:
$("#div1").insertAfter("#div2");
Run Code Online (Sandbox Code Playgroud)
这会将id为'div1'的元素移动到id为'div2'的元素之后.这假设您从id属性中删除了'#'.
从现在开始支持flexbox,你也可以使用它来仅使用css重新排序div:
<div id="container">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
</div>
Run Code Online (Sandbox Code Playgroud)
和css:
#container{
display: flex;
flex-direction: column;
}
#div2{
order:2
}
#div3{
order:1
}
Run Code Online (Sandbox Code Playgroud)
它会显示:
1
3
2
Run Code Online (Sandbox Code Playgroud)
你可以试试这个小提琴.
小智 5
你可以用 JavaScript 来做:
function reOrder() {
divOne = document.getElementById('#div1');
divTwo = document.getElementById('#div2');
divThree = document.getElementById('#div3');
container = divOne.parentNode;
container.appendChild(divTwo);
container.appendChild(divOne);
container.appendChild(divThree);
}
Run Code Online (Sandbox Code Playgroud)
编辑:修复了 ID 中的拼写错误。