Uncaught TypeError: Невозможно прочитать свойство 'offsetTop' из null - PullRequest
0 голосов
/ 27 сентября 2018

Я использую HTML, CSS и JavaScript для создания веб-страницы с липкой и отзывчивой панелью навигации.Я создал адаптивную панель навигации и пытаюсь сделать ее липкой.Проблема в том, что он не залипает и выдает ошибку: Uncaught TypeError: Невозможно прочитать свойство 'offsetTop' со значением NULL

HTML-код:

<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#career">Careers</a>
<a href="#fellowship">About Us</a>
<a href="javascript:void(0);" class="icon" onclick="myFunctionForResponsive()">
    <i class="fas fa-bars"></i>
</a>
</div>

Код JavaScript:

// When the user scrolls the page, execute myFunction 
window.onscroll = function() {myFunctionForSticky()};

// Get the navbar
var navbar = document.getElementById("myTopnav");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. 
Remove "sticky" when you leave the scroll position
function myFunctionForSticky() {
    if(window.pageYOffset >= sticky){
    console.log("window.pageYOffset >= sticky");
}
else{
    console.log("Not window.pageYOffset >= sticky");
}
 if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky");
  } else {
    navbar.classList.remove("sticky");  
  }
}

/*Toggle between adding and removing the "responsive" class to topnav
when the user clicks on the icon*/

function myFunctionForResponsive() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}

Если я беру класс вместо идентификатора, то он показывает ошибку: Uncaught TypeError: Невозможно прочитать свойство 'remove' из неопределенного

1 Ответ

0 голосов
/ 27 сентября 2018

Код, который хочет получить доступ к DOM, должен быть помещен в прослушиватель событий, который прослушивает DOMContentLoaded.

В настоящее время вы пытаетесь получить доступ к элементу с идентификатором myTopnav, когда браузер не обнаружил 't проанализировал HTML, что означает, что ваш document.getElementById("myTopnav"); возвращает null.В следующей строке кода вы пытаетесь прочитать свойство offsetTop null, которое вернул ваш document.getElementById("myTopnav"), в результате чего Cannot read property 'offsetTop' of null.

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

document.addEventListener('DOMContentLoaded', function() {
  // When the event DOMContentLoaded occurs, it is safe to access the DOM

  // When the user scrolls the page, execute myFunction 
  window.addEventListener('scroll', myFunctionForSticky);

  // Get the navbar
  var navbar = document.getElementById("myTopnav");

  // Get the offset position of the navbar
  var sticky = navbar.offsetTop;

  // Add the sticky class to the navbar when you reach its scroll position. 
  // Remove "sticky" when you leave the scroll position

  function myFunctionForSticky() {
    if (window.pageYOffset >= sticky) {
      console.log("window.pageYOffset >= sticky");
    } else {
      console.log("Not window.pageYOffset >= sticky");
    }
    if (window.pageYOffset >= sticky) {
      navbar.classList.add("sticky");
    } else {
      navbar.classList.remove("sticky");
    }
  }

  /*Toggle between adding and removing the "responsive" class to topnav
  when the user clicks on the icon*/

  function myFunctionForResponsive() {
    navbar.classList.toggle('responsive');
  }
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...