javascript - 移动到顶部的垂直导航栏

标签 javascript html css navigation

我试图让我的垂直导航栏在用户滚动时移动到顶部(原来的位置不在顶部)。 我只知道 HTML、CSS 和 JavaScript,所以我不知道 jQuery。 这是导航栏的代码:

类名或 ID 名有问题还是 JavaScript 代码有问题?

	

	var body = document.getElementsByTagName("body")[0];
	var navigation = document.getElementById("navigation");
	window.addEventListener("scroll", navigationFixing());
	function navigationFixing() {
		if (body.scrollTop > navigation.getBoundingClientRect().bottom)
		{navigation.className = "fixedNavigation";
	}
		else {
			navigation.className = "notFixedNavigation";
		}
	}
#navigation {list-style-type: none;
	width: 15%;
	margin: 0px;
	padding: 0px;
	font-size: 35px;
	border: 1px solid;
	height: 100%;
	background-color: #d6d6c2;
	overflow: auto;
	position: absolute;
	}
.navigationbar {
	border-bottom: 1px solid black;
	}
.navigationbar a {display: block;
	  background-color: #C0C0C0; 
	  padding-left: 10px;
	  padding-bottom: 16px;
	  text-decoration: none;
	  color: #ffffff;
	  }
.navigationbar a:hover {background-color: #404040;
			color: white;}	  
.navigationbar a.nuvarande {background-color: black; 
}

.fixedNavigation {
	position: fixed;
	top: 0;
	left: 0;
}
.notFixedNavigation {
	position: absolute;
}
<ul id="navigation" class="notFixedNavigation">
			<li class="navigationbar">
				<a href="index.html">Home</a>
			</li>
			<!---------------DATOR-------------------
			<li class="navigationbar">
				<a href="play.html">Play</a>
			</li>
			---------------------------------------->
			<li class="navigationbar">
				<a href="" class="nuvarande">Rules</a>
			</li>
			<li class="navigationbar">
				<a href="tactics.html">Tactics</a>
			</li>
			<li class="navigationbar">
				<a href="contact.html">Contact</a>
			</li>
		</ul>

最佳答案

您关心的是立即调用您的事件处理程序,而不是将其附加到监听器。移除括号。

window.addEventListener("scroll", navigationFixing);

另外,navigation.getBoundingClientRect().bottom会随着位置的变化而变化。最好在函数外设置。

var pos = navigation.getBoundingClientRect().bottom;
function navigationFixing() {
  if (body.scrollTop > pos) {...}
}

另请注意@bestinamir,您的 CSS 已被覆盖。它需要一些工作,但您可以从以下方面着手:

.fixedNavigation {
  position: fixed !important;
  top: 0;
  left: 0;
}

关于javascript - 移动到顶部的垂直导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051963/

相关文章:

jquery - 灵活的 Div 高度和宽度

javascript - 我无法将对象属性作为函数获取

javascript - 响应 header 中未设置 JWT token

php - 在移动设备上选择输入文本时,不将输入文本居中

html - 在 li 标签中显示空格

javascript - jQuery .css() 方法不起作用

javascript - AntD rowSelection 功能组件

javascript - jQuery 将页脚贴在页面底部

jQuery onInput 识别换行符

html - 我在一个 div 中有 p 元素,它们的高度都为 50px。为什么p向下移动?