退出在到达屏幕末尾时创建 div 的 for 循环

Exiting a for loop that creates divs when reached end of screen

我正在尝试完成一个小练习,当点击中间的大按钮并且小点改变颜色时刷新页面。 我已停止页面滚动,因此页面充满了点,但我注意到溢出 属性 在不同的浏览器上表现不同。然后我想到另一个问题,在手机或平板上,这些点又会显示不同! 所以我不确定这是否可能,但期望的结果是循环创建点,直到屏幕填满并且按钮显示在屏幕中间。 有人可以告诉我这个想法是否可行,因为我找不到任何类似的问题。或者是否有更好的方法来获得我想要的结果。另外,如果您有时间,能否简要解释一下原因,因为我想了解它的工作原理并从中学习。 所以... 这是 JavaScript

var htmlDot = "";
var red;
var green;
var blue;
var rgbColor;


function colourSelect() {
    return Math.floor(Math.random() * 256 );
}

for(var i = 1; i<=100; i+=1) {
    red = colourSelect();
    green = colourSelect();
    blue = colourSelect();
    rgbColor = "rgb(" + red + "," + green + "," + blue + ")";
    htmlDot += "<div style=\"background-color:"+ rgbColor + " \"></div>";
}
document.write(htmlDot);

这是HTML

<!doctype html>
<html>
<head>

     <link rel="stylesheet" href="main.css"> 
</head>
<body>
    <button id="refresh">Click Me!</button>
    <script src="script.js"></script>
</body>
</html>

这是CSS

  body {
    position: relative;
    overflow: hidden;
}

#refresh {
    font: 40px bold;
    font-family: sans-serif;
    width: 200px;
    height: 200px;
    display: inline-block;
    border-radius: 50%;
    margin: 5px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    background-color: rgb();
}
div {
    width: 50px;
    height: 50px;
    display: inline-block;
    border-radius: 50%;
    margin: 5px;
 }

提前致谢

在给定浏览器 window.

的情况下,您必须计算出适合您的浏览器 window 的点数,而不是使用 100 作为点数
var w = window.innerWidth; // browser width
var h = window.innerHeight; // browser height
var size = 60; // 50px + 5px + 5px (width or height) + (left or top margin) + (right or bottom margin)
var hdots = Math.floor(w/size); // how many dots fit horizontally
var vdots = Math.floor(h/size); // how many dots fit vertically
var numDots = hdots * vdots;

我想你正在寻找这样的东西:

https://jsbin.com/racahapevi/edit?html,css,js,output

要点:

  • 计算可以水平放置的点数
  • 计算总点数
  • <html><body> 宽度和高度定义为视口的 100%
  • 溢出:隐藏在html,所以不会有滚动
  • 给按钮添加onclick事件。

这里是一些代码:

var numDots = hdots * vdots;

while(numDots--){
    red = colourSelect();
    green = colourSelect();
    blue = colourSelect();
    rgbColor = "rgb(" + red + "," + green + "," + blue + ")";
    htmlDot += "<div class='dot' style=\"background-color:"+ rgbColor + " \"></div>";
}