粘性导航菜单滚动时无法正常工作-Wordpress

时间:2018-09-20 13:30:30

标签: javascript wordpress

我已从W3schools中复制了以下内容,但是滚动时导航不固定在屏幕顶部。

https://www.w3schools.com/howto/howto_js_navbar_sticky.asp

我使用了以下代码:

  <div id="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  </div>
/* Style the navbar */
#navbar {
  overflow: hidden;
  background-color: #333;
}

/* Navbar links */
#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}

/* Page content */
.content {
  padding: 16px;
}

/* The sticky class is added to the navbar with JS when it reaches its scroll position */
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}



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

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

// 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 myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

当我检查Google控制台时,错误似乎是:

“未捕获的键入错误:无法读取null的属性” offsettop”

“未捕获的Typerror:无法读取空的属性“ ClassList””

我对JS还是很陌生,因此非常感谢您提供任何帮助!

0 个答案:

没有答案