2 回答

TA貢獻1811條經驗 獲得超5個贊
Use flexbox :
.wrapper{
display :flex;
flex-direction: column-reverse;
}
<div class='wrapper'>
<p>A</p>
<p>B</p>
<p>C</p>
</div>

TA貢獻1880條經驗 獲得超4個贊
使用 CSS
您可以通過指定顯示來反向排序項目flex。
div {
display: flex;
flex-direction: column-reverse;
}
<div>
<p>A</p>
<p>B</p>
<p>C</p>
</div>
或者,您可以通過沿方向軸翻轉子元素來轉換子元素。翻轉整個div,然后p在 div 內翻轉每個。雖然這有效,但應該避免使用flex. 注意:轉換元素后,選擇會變得非常不穩(wěn)定。
div, p {
transform: scale(1, -1);
}
<div>
<p>A</p>
<p>B</p>
<p>C</p>
</div>
使用 JavaScript
您也可以在 JavaScript 中使用一個函數(shù)來執(zhí)行此操作,該函數(shù)遍歷節(jié)點childNodes并將它們插入到第一個子節(jié)點之前。
/**
* @describe Reverses the child nodes of a node in-place.
* @param {Node} node - The parent of the child nodes to be reversed
*/
const reverseChildNodes = node => {
for (let i = 1; i < node.childNodes.length; i++) {
node.insertBefore(node.childNodes[i], node.firstChild);
}
}
if (Element.prototype.reverseChildren === undefined) {
Element.prototype.reverseChildren = function() {
reverseChildNodes(this);
};
}
// Global function
reverseChildNodes(document.querySelector('.section:first-child'));
// Prototype method on Node object
[...document.querySelectorAll('.section')].pop().reverseChildren();
.section { border: thin solid grey; margin: 0.25em; padding: 0.25em; }
<div class="section">
<p>A</p>
<p>B</p>
<p>C</p>
</div>
<div class="section">
<p>A</p>
<p>B</p>
<p>C</p>
</div>
添加回答
舉報