为什么不能在JavaScript中设置导航栏的高度?

时间:2018-08-06 06:27:52

标签: javascript

我想知道如何使用HTML,CSS和JS编写粘性​​navbar。我没有使用jQuery创建了粘性导航,但是height函数无法正常工作。有人可以建议我如何调用此height函数吗?如何在纯JavaScript中找到height

document.addEventListener("DOMContentLoaded", function() {
  'use strict';
  var c, currentScrollTop = 0;
  var navbar = document.querySelector(".nav");
  window.addEventListener('scroll', function() {
    var a = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    var b = navbar.hight();
    currentScrollTop = a;
    if (c < currentScrollTop && a > b + b) {
      navbar.addClass("scrollUp");
    } else if (c > currentScrollTop && !(a <= b)) {
      navbar.removeClass("scrollUp");
    }
    c = currentScrollTop;
  });
});
<nav>
  <div class="container">
    <a href="#" id="brand">Brand</a>
    <button>
      <span></span>
      <span></span>
      <span></span>
    </button>
    <ul class="navbar-menu">
      <li>
        <a href="#">Home</a>
      </li>
      <li>
        <a href="#">About</a>
      </li>
      <li>
        <a href="#">Team</a>
      </li>
      <li>
        <a href="#">Timeline</a>
      </li>
      <li>
        <a href="#">Conact</a>
      </li>
    </ul>
  </div>
</nav>

1 个答案:

答案 0 :(得分:2)

nav不是课程。这是一个HTML标记。因此,document.querySelector(".nav")将返回一个空节点列表。

更改

document.querySelector(".nav")

var b = navbar.height();

document.querySelector("nav")

var b = navbar.clientHeight;
// or
var height = navbar.offsetHeight;

document.addEventListener("DOMContentLoaded", function() {
  'use strict';
  var c, currentScrollTop = 0;
  var navbar = document.querySelector("nav");
  window.addEventListener('scroll', function() {
    var a = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    var b = navbar.clientHeight
    currentScrollTop = a;
    if (c < currentScrollTop && a > b + b) {
      navbar.addClass("scrollUp");
    } else if (c > currentScrollTop && !(a <= b)) {
      navbar.removeClass("scrollUp");
    }
    c = currentScrollTop;
  });
});
<nav>
  <div class="container">
    <a href="#" id="brand">Brand</a>
    <button>
      <span></span>
      <span></span>
      <span></span>
    </button>

    <ul class="navbar-menu">
      <li>
        <a href="#">Home</a>
      </li>
      <li>
        <a href="#">About</a>
      </li>
      <li>
        <a href="#">Team</a>
      </li>
      <li>
        <a href="#">Timeline</a>
      </li>
      <li>
        <a href="#">Conact</a>
      </li>
    </ul>
  </div>
</nav>