How to modify grid-template-areas with javascript

前端 未结 3 675
南笙
南笙 2020-12-20 12:13

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:

相关标签:
3条回答
  • 2020-12-20 12:50

    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>

    0 讨论(0)
  • 2020-12-20 13:09

    with styled-components

    
    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"]} >
    )
    
    
    
    0 讨论(0)
  • 2020-12-20 13:16

    just change to elem.style.gridTemplateAreas ='"z z z" "a b c" "d e f"';

    0 讨论(0)
提交回复
热议问题