【问题标题】:Decrease JS value gradually when nearing the bottom of the div接近 div 底部时逐渐减小 JS 值
【发布时间】:2022-01-15 20:03:12
【问题描述】:

我有一个背景 div,其中星星(就像在宇宙中一样)被放置在随机的位置,并且具有随机的宽度和高度。现在我想在页面顶部有很多星星,并且你离页面顶部越远,我希望星星越少。所以我可能想减少一个 JS 变量。 我已经尝试过创建单独的 div,每个 div 包含的星数较少,但 div 之间的差距有点明显。

这个函数会将 Star.svg 分散在整个 div 中,但我希望在接近底部 div 的末尾时星星的数量逐渐减少。 函数示例:

<div class="stars1" id="stars1"></div> <!-- this div is 100vh -->

funtion starGen() {
    var amount1 = Math.floor(Math.random() * 100) + 5;
    var divWidth = document.getElementById("stars1").clientWidth - 30;
    var divHeight = document.getElementById("stars1").clientHeight - 30;

    for (let i = 0; i < amount1; i++) {
      var img = document.createElement("img");
      var top = Math.floor(Math.random() * divHeight);
      var right = Math.floor(Math.random() * divWidth);
      img.src = "./assets/img/Star 6.svg";
      img.height = Math.floor(Math.random() * 25) + 5;
      img.width = 20;
      img.style.position = "absolute";
      img.style.top = top + "px";
      img.style.left = right + "px";
      document.getElementById("stars1").appendChild(img);
    } 

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:

    说明:

    Math.random() 将生成一组均匀分布的随机数。这对于星星的正确位置很好,但对于星星的顶部位置,您需要一组指数分布的数字,这些数字在顶部出现更常见。

    生成的示例:

    Generated Starry Sky

    代码:

    来源:https://jsfiddle.net/tvmgs37w/

    摘录:

    function starGen() {
      var amountOfStars = Math.floor(Math.random() * 100) + 5;
      var divWidth = document.getElementById("starrySky").clientWidth - 30;
      var divHeight = document.getElementById("starrySky").clientHeight - 30;
    
      for (let i = 0; i < amountOfStars; i++) {
        var star = document.createElement("div");
        var top = Math.floor(randomExponential() * divHeight);
        var right = Math.floor(Math.random() * divWidth);
        star.textContent = "*";
        star.height = Math.floor(Math.random() * 25) + 5;
        star.width = 20;
        star.style.position = "absolute";
        star.style.top = top + "px";
        star.style.left = right + "px";
        star.style.color = "yellow";
        document.getElementById("starrySky").appendChild(star);
      }
    }
    
    function randomExponential() {
            var u = Math.random();
            var mu = 1.5;
            return -Math.log(1.0 - u) / mu;
    }
    
    starGen();
    &lt;div class="starrySky" id="starrySky" style="width:100vw; height:100vh;background-color:darkblue"&gt;&lt;/div&gt; &lt;!-- this div is 100vh --&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多