简体   繁体   中英

How to divide window.innerWidth by div.style.width in JavaScript?

I'm trying to create divs along the screen. I want the number of divs to be equal to the screen's width (1920px) / 1em (font size width). I'm having difficulty and I don't know what I'm doing wrong.

function main(){
  var div = document.createElement('div');
  div.style.width = '1em';
  div.style.height = '1em';
  div.style.background = 'red';
  i = 0;
  while(i < (window.innerWidth / div.style.width)){
    document.body.appendChild(div);
    i++;
  }
}
main();

You can try the below code to create the div according to screen width. You have to convert the 1em value to px by using

var em = parseFloat(getComputedStyle(document.documentElement).fontSize);

 function main() { var em = parseFloat(getComputedStyle(document.documentElement).fontSize); console.log(window.innerWidth, em, (window.innerWidth / em)) for (i = 0; i < (window.innerWidth / em); i++) { var div = document.createElement('div'); div.style.width = '1em'; div.style.height = '1em'; div.style.background = 'red'; document.body.appendChild(div); } } window.onload = function() { main(); }; 
 div { margin-bottom: 1px; } 
 <body id="body"></body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM