如何使用javascript修改网格模板区域

RMo*_*RMo 8 html javascript css

我一直在尝试grid-template-areas用javascript 修改.我elem.style在DOM 中的css属性list()中找到了一个名为:的属性gridTemplateAreas.但我似乎无法用javascript改变它.

如何grid-template-areas使用javascript 修改-property?

这是我试过的代码:

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.");
});
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
<h3>Click to activate the code</h3>
<div id="grid">
<div id="div1"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

PS:我正在使用Google Chrome atm

Mic*_*ter 13

您的 elem.style.gridTemplateAreas = "z z z" "a b c" "d e f"

不是有效的陈述,也不是你想做的事.您想要分配值"z z z" "a b c" "d e f".因此,你需要用这样的引号括起来:elem.style.gridTemplateAreas = '"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.");
});
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
<h3>Click to activate the code</h3>
<div id="grid">
<div id="div1"></div>
</div>
Run Code Online (Sandbox Code Playgroud)


小智 5

只需更改为elem.style.gridTemplateAreas ='"z z z" "a b c" "d e f"';