簡體   English   中英

你能在 CSS 和 JavaScript 中動態改變 flexbox 的 flex-direction 嗎?

[英]Can you change the flex-direction of flexbox dynamically in CSS and JavaScript?

給定一個變量 isRow,如果為真,我想顯示 flex-direction: 行,但如果為假,我想顯示 flex 方向:列。

如果有一種方法可以與我嘗試的方法不同,請告訴我!

 document.getElementsByClassName("flex-container")[0].style.flex-direction = "row"; //can I use: document.getElementById("flex-cointainer") instead?
 .flex-container { display: flex; flex-direction: column; background-color: DodgerBlue; } .flex-container > p { background-color: #f1f1f1; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; }
 <div class = "flex-container"> <p id="p1">Hello World!</p> <p id="p2">Hello World!</p> </div>

您應該將style.flex-direction更改為style.flexDirection以及您的評論,是的,您可以使用document.getElementById("flex-cointainer")但首先您必須將 id 添加到您的元素中,例如

<div class="flex-container" id="flex-container">

這是完整的工作代碼:

 var isRow = true; var myContainer = document.getElementById("flex-container"); if(isRow) { myContainer.style.flexDirection = "row"; }else { myContainer.style.flexDirection = "column"; }
 #flex-container { display: flex; flex-direction: column; background-color: DodgerBlue; } #flex-container > p { background-color: #f1f1f1; width: 100px; margin: 10px; text-align: center; line-height: 75px; font-size: 30px; }
 <!DOCTYPE html> <html> <head> <title>Test</title> <head> <body> <div id="flex-container"> <p id="p1">Hello World!</p> <p id="p2">Hello World!</p> </div> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM