【问题标题】:ERROR TypeError: Cannot read properties of null (reading 'classList') in styles.css错误类型错误:无法在styles.css 中读取null 的属性(读取'classList')
【发布时间】:2021-12-26 09:31:42
【问题描述】:

所以,当 scrollY 超过 30 像素时,我尝试将背景颜色更改添加到我的导航栏,但它仍然有效。但是我在控制台上遇到了这个错误,因为当它超过 30px 时,它无法将新的 classList 添加到标题中。

这是我的 .ts 文件

ngOnInit(): void {   
    function scrollHeader(){
      const nav = document.getElementById('header');
      if(window.scrollY >= 30){ 
        nav.classList.add('scroll-header');
      }else{
        nav.classList.remove('scroll-header');
      }
    }
    window.addEventListener('scroll', scrollHeader);
  }

这是样式文件:

.scroll-header{
    background: #242526;
    color: white;
}

.scroll-header .wrapper .logo a{
    color:white;
}

这是 HTML 文件:

<nav id="header">
    <div class="wrapper">
        <div class="logo">
            <a [routerLink]="'/'">InsuranceBazaar</a>
        </div>
        <input type="radio" name="slider" id="menu-btn">
        <input type="radio" name="slider" id="close-btn">

        <ul class="nav-links">
            <label for="close-btn" class="btn close-btn">
                <i class="fa fa-times"></i>
            </label>
            
            <li>
....

我不知道错误是什么,但我猜是因为 ngOnInit()。如果有人知道如何解决此错误,请分享答案。

【问题讨论】:

  • 在执行此代码时似乎没有呈现id="header" 元素。你能提供一段有标题的代码吗?
  • 当然。我已经添加了 HTML 文件

标签: css angular angularjs typescript typeerror


【解决方案1】:

你的函数被正确调用了吗?

也许你应该尝试不使用ngOnInit()

然后尝试用console.log()检查滚动? 或者也许更具体地尝试#header.scroll-header 然后你的风格......

【讨论】:

  • 实际上在ngOnInit()函数之外,是不能调用windows对象的。如果我在 ngOnInit() 之外添加 windows.addEventListener() 会引发错误
猜你喜欢
  • 2021-11-07
  • 2021-01-15
  • 2015-01-14
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 2023-01-31
  • 2017-11-15
相关资源
最近更新 更多