使用Vanilla Javascript检测滚动以帮助更改导航CSS [英] Using Vanilla Javascript to detect scroll to help make change to navigation CSS

查看:48
本文介绍了使用Vanilla Javascript检测滚动以帮助更改导航CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从高度为80px的固定顶部导航中检测到页面滚动是否超过100px.

I am attempting to detect scroll on a page if it exceeds 100px from a fixed top navigation that has a height of 80px.

计划是,一旦用户滚动超过所提到的100px,导航栏将更改背景颜色.

The plan is that once the user's scroll, exceeds the mentioned 100px, the navbar will change background color.

我看过很多关于该主题的教程,但是我所看到的所有教程都在使用Jquery.我希望使用Vanilla Javascript做到这一点.

I have seen a lot of tutorials on the subject, but all those I have seen are using Jquery. I wish to make this using Vanilla Javascript.

推荐答案

,您可以使用 window.onscroll 检测滚动以及 window.pageYOffset 文档.documentElement.scrollTop 属性可获取窗口的滚动位置.下面是您描述的方案的代码段:

you can use window.onscroll to detect scroll and window.pageYOffset or document.documentElement.scrollTop properties to get the scroll position of window. below is a code snippet for your scenario you described:

window.onscroll = function(){
var top =	 window.pageYOffset || document.documentElement.scrollTop;
if (top > 100) {
	document.getElementById('nav').style.background = "blue";
} else {
	document.getElementById('nav').style.background = "yellow";
}
};

nav {
  position:fixed;
  height:100px;
  width:100%;
  top:0;
  background:yellow;
  display:block;
}

<nav id="nav">
  Hello
</nav>
<div style="height:700px;">
  
</div>

这篇关于使用Vanilla Javascript检测滚动以帮助更改导航CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆