我一直在嘗試用javascript修改網格模板區域。我在DOM中的css屬性列表(elem.style)中找到了一個屬性,叫做:gridTemplateAreas。但我似乎無法用javascript改變它。
如何用javascript修改grid-template-areas屬性?
以下是我嘗試的代碼:
window.addEventListener("click", function(){
let elem= document.getElementById("grid");
elem.style.gridTemplateAreas =
"z z z"
"a b c"
"d e f"
console.log("The grid-template area should have been redefined now. The blue block should have move to the top row.");
});
#grid{
width: 100px;
height: 100px;
background-color: red;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-template-areas: "x x x"
"y y z"
"y y z";
}
#div1{
background-color: blue;
grid-area: z;
}
<h3>Click to activate the code</h3>
<div id="grid">
<div id="div1"></div>
</div>
your elem . style . grid template areas = “z z z” "甲乙丙丁" "德·英·法"
不是有效的語句,或者它沒有執行您想要執行的操作。 你想給值" z z z" "a b c" "d e f "。所以,你需要用這樣的引號把它括起來:elem . style . gridtemplatareas = ' " z z z " " a b c " " d e f " ';
window.addEventListener("click", function(){
let elem= document.getElementById("grid");
elem.style.gridTemplateAreas = '"z z z" "a b c" "d e f"';
console.log("The grid-template area should have been redefined now. The blue block should have move to the top row.");
});
#grid{
width: 100px;
height: 100px;
background-color: red;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-template-areas: "x x x"
"y y z"
"y y z";
}
#div1{
background-color: blue;
grid-area: z;
}
<h3>Click to activate the code</h3>
<div id="grid">
<div id="div1"></div>
</div>
只需改成elem . style . gridtemplatareas = ' " z z z " " a b c " " d e f " ';
使用樣式組件
const Grid = styled.div`
width: 100px;
height: 100px;
background-color: red;
display: grid;
grid-template-areas: ${(props) => props.areas
? props.areas.reduce((acc, str) => (acc += `${"'" + str + "'" + "\n"}`), ``) + ";"
: "none"};
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
`
const StyledGrid = () => (
<Grid areas={["z z z", "a b c", "d e f"]} >
)