滚动导航栏在固定位置时会丢失一些格式

时间:2015-03-06 13:02:05

标签: javascript html css

我是Javascript的新手,我正在尝试学习如何滚动导航栏。看来我已将滚动部分钉住,但由于某种原因,一旦导航栏设置为固定,左偏移似乎会改变。最初,酒吧会向左侧突然移动。将包含div的宽度设置为100%会使条形更加居中,但它仍处于关闭状态。此外,我似乎无法正确地按下按钮。

// Javascript

window.onload = function() {
  var navbar = document.getElementById("navbar");
  var navbarY = navbar.offsetTop;

  window.onscroll = function() {

    if (window.scrollY >= navbarY) {
      navbar.style.position = "fixed";
      navbar.style.top = "0";
    } else if (window.scrollY < navbarY) {
      navbar.style.position = "static";
    }
  }
};
/***CSS***/

/*HEADER*/

#header {
  border: 1px solid;
  height: 150px;
  margin: 0 200px 0 200px;
}
/*NAVIGATION BAR*/

#navbar {
  width: 100%;
}
#navbar ul {
  background: none;
  border: 1px solid;
  border-radius: 5px;
  height: 50px;
  list-style: none;
  margin: 0 200px 0 200px;
  position: static;
  top: auto;
}
#navbar ul li {
  margin: 0;
}
#navbar ul li a {
  background: white;
  border: 1px solid black;
  border-radius: 5px;
  color: black;
  float: left;
  font: bold 1em Arial, san-serif;
  margin: 0;
  padding: 10px 30px;
  text-decoration: none;
}
#navbar ul li a:hover {
  background: black;
  border: 1px solid black;
  border-radius: 5px;
  color: white;
  font: bold 1em Arial, san-serif;
  padding: 10px 30px;
  text-decoration: none;
}
/*CONTAINER*/

#container {
  border: 1px solid;
  height: 2000px;
  margin: 0 200px 0 200px;
}
<!-- HTML -->

<!DOCTYPE html>
<html lang="en-US">

<head>
  <meta charset="UTF-8">
  <title>Test</title>
  <link rel="stylesheet" href="Test.css" />
  <script src="Test.js"></script>
</head>

<body>
  <div id="header">

  </div>
  <div id="navbar">
    <ul>
      <li><a href="#">Home</a>
      </li>
      <li><a href="#">Content</a>
      </li>
      <li><a href="#">About</a>
      </li>
    </ul>
  </div>
  <div id="container">

  </div>
</body>

</html>

0 个答案:

没有答案