Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

html - How to modify grid-template-areas with javascript

I have been trying to modify grid-template-areas with javascript. I found a property in the css properties list (elem.style) in the DOM called: gridTemplateAreas. But I seem to be unable to change it with javascript.

How do i modify the grid-template-areas-property with javascript?

Here is the code I tried:

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Is not a valid statement or it does not do what you want to do. You want to assign the value "z z z" "a b c" "d e f". Therefore, you need to surround it by quotes like this: 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.");
});
#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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...