[英]Can you change the flex-direction of flexbox dynamically in CSS and JavaScript?
Given a variable, isRow, if true I want to display the the flex-direction: row but if it is false I want to the flex direction: column.给定一个变量 isRow,如果为真,我想显示 flex-direction: 行,但如果为假,我想显示 flex 方向:列。
If there is a way to do this differently than what I am attempting, please let me know!如果有一种方法可以与我尝试的方法不同,请告诉我!
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>
you should change style.flex-direction
to style.flexDirection
and about your comment , yes you can use document.getElementById("flex-cointainer")
but first you have to add id to your element like您应该将
style.flex-direction
更改为style.flexDirection
以及您的评论,是的,您可以使用document.getElementById("flex-cointainer")
但首先您必须将 id 添加到您的元素中,例如
<div class="flex-container" id="flex-container">
and here is full working code :这是完整的工作代码:
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.