
为什么要制作导航置顶效果呢?导航置顶可以让用户更好的快速找到页面的各个内容,旨在提升用户体验、提高导航可见性、 节省页面空间等方面。
原理
使用javaScript向window对象(浏览器窗口)添加滚动事件监听器,通过CSS的position: fixed属性,可以将导航栏固定在页面顶部。 当页面滚动到一定位置时,通过JavaScript动态改变导航栏的样式,使其固定在页面顶部。
关键技术点
添加滚动事件监听器
判断滚动条滚动的距离和计算元素在页面上的垂直位置
通过CSS添加或者删除 position: fixed属性
主要js代码与解析
<script> //JavaScript向window对象(浏览器窗口)添加滚动事件监听器 window.addEventListener("scroll", () => { //获取滚动条滚动的距离 //由于在不同情况下,document.body.scrollTop与document.documentElement.scrollTop 都有可能取不到值 //但是这两个方法有一个特点:两个方法同时使用只有一个值有效,比如document.body.scrollTop能取到值的时候,document.documentElement.scrollTop就会始终为0;反之亦然。 let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //计算元素在页面上的垂直位置 offsetTop属性表示元素顶部边缘到其视口顶部边缘的距离 let offsetTop = document.querySelector('#nav').offsetTop; if (scrollTop > offsetTop) { document.querySelector('#nav').style.position = "fixed"; document.querySelector('#nav').style.top = "0"; } else { document.querySelector('#nav').style.position = ""; document.querySelector('#nav').style.top = ""; } }) </script>
在这个示例中,nav是导航容器的id,通过判断滚动条滚动的距离和元素在页面上的垂直位置使用javaScript添加或者删除 CSS的position: fixed属性, offsetTop属性是指元素相对于其offsetParent元素的顶部位置的距离。如果滚动条滚动的距离大于元素在页面上的垂直位置,添加fixed属性,反之删除fixed属性