【问题标题】:Exiting a for loop that creates divs when reached end of screen退出一个在到达屏幕末尾时创建 div 的 for 循环
【发布时间】:2017-01-08 17:42:31
【问题描述】:

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

提前谢谢你

【问题讨论】:

  • 在添加到 DOM 后检查每个 div 的偏移量。如果 Offsettop+height 的最外边超出 window.height 则停止/从循环返回,否则继续。很简单。
  • 虽然逻辑很简单,但实现起来可能需要一些努力。
  • 我已经为那些圈子头疼了。 :)
  • 我也是,一直看着它们太久了,我闭上眼睛看到点:-D

标签: javascript css for-loop responsive screen-size


【解决方案1】:

我认为您正在寻找这样的东西:

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

关键点:

  • 计算可以水平放置的点数
  • 计算点的总数
  • &lt;html&gt;&lt;body&gt; 的宽度和高度定义为视口的 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>";
}

【讨论】:

  • 非常感谢您花时间解释您的步骤并分享此 jsbin。我真的很感激
  • 没问题@Jessica,但记得接受答案并祝学习过程顺利:)
【解决方案2】:

除了使用 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;

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 2022-08-12
    • 1970-01-01
    • 2021-07-25
    • 2016-11-04
    • 2015-01-13
    • 2021-01-23
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多