在 CSS 或 javascript 中更改 div 顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4699594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change div order in CSS or javascript
提问by Sam Holder
say I have layout like so:
说我有这样的布局:
<div id="main">
<div id="NormalContent">
{some content which is a fixed length list}
</div>
<div id="FeaturedContent">
{some content which may contain a long list}
</div>
</div>
and I want to place FeaturedContent above NormalContent.
我想将 FeaturedContent 放在 NormalContent 之上。
Can I do this with CSS? I assume I can with Javascript?
我可以用 CSS 做到这一点吗?我假设我可以使用 Javascript?
采纳答案by sevenseacat
In Javascript you could simply reorder them on the page.
在 Javascript 中,您可以简单地在页面上重新排序它们。
With CSS it would be possible to swap them left and right if they were side by side (with some conditions), but not one above the other.
使用 CSS,如果它们并排(在某些条件下),则可以左右交换它们,但不能一个在另一个之上。
回答by Hemlock
For a non-jquery answer
对于非 jquery 答案
var content = document.getElementById('FeaturedContent');
var parent = content.parentNode;
parent.insertBefore(content, parent.firstChild);
Note that there is no need to remove it from the DOM, adding it a second time will move it.
请注意,不需要从 DOM 中删除它,第二次添加它会移动它。
回答by davin
this is a clearer way to move them with 1 line of jQuery:
这是使用 1 行 jQuery 移动它们的更清晰的方法:
$('#FeaturedContent').prependTo('#main');
回答by Jimmy Chandra
If you know exactly the dimension of FeaturedContent & NormalContent, you might be able to get away with using position:relative and playing around w/ their top properties.
如果您确切地知道 FeaturedContent 和 NormalContent 的维度,您可能可以使用 position:relative 并使用它们的顶级属性来解决问题。
i.e.
IE
#NormalContent {
position:relative;
top:22px;
}
#FeaturedContent {
position:relative;
top:-22px;
}
But to make them flow... hmm... not sure you can do that.
但是为了让它们流动……嗯……不确定你能不能做到。
With jQuery you can do something like:
使用 jQuery,您可以执行以下操作:
$("#NormalContent").remove().insertAfter($("#FeaturedContent"));
回答by chocolata
This answer seems to work aswel. CSS(3) only, very elegant solution.
这个答案似乎也有效。仅 CSS(3),非常优雅的解决方案。
CSS have a div that's to the right below the left div. Divs are reverse in HTML

