【问题标题】:Maximum call stack size exceeded , on an scroll function在滚动函数上超出最大调用堆栈大小
【发布时间】:2022-07-06 18:45:42
【问题描述】:

我是一个完整的java脚本初学者,我自己无法理解这个函数有什么问题:(我想在滚动时更改背景颜色。

function whenScroll() {
  if (whenScroll() > 45) {
    document.getElementsByTagName("body")[0].style.backgroundColor = "#0f0f0f";
  }
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您在whenScroll() 中调用whenScroll(),因此您的代码中存在无限递归。这就是您收到此错误的原因。

    一种解决方案是使用不同的方法来跟踪滚动,例如使用变量:

    let scrolled = 0;
    // ...
    function whenScroll() {
    
      scrolled += 10;  // Whatever ammount you wish for
    
      if (scrolled > 45) {
        document.getElementsByTagName("body")[0].style.backgroundColor = "#0f0f0f";
      }
    }
    

    【讨论】:

    • 为什么投反对票?
    • 你是对的错误,但你的代码......不是那么多......在处理观看滚动时,不断向该函数内部的“滚动”添加任意数字是没有意义的页面位置
    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2015-10-24
    • 2015-12-29
    • 2017-12-27
    • 2020-12-06
    • 2021-01-21
    • 2018-02-06
    相关资源
    最近更新 更多