
本文介绍如何使用jQuery制作当鼠标滚动的时候导航固定功能,导航固定置顶可以让用户更好的快速找到页面的各个内容,旨在提升用户体验、提高导航可见性、 节省页面空间等方面。
主要js代码与解析
<script> $(function () { //jQuery导航固定 var fixed = $(".header"); //获取header position属性 var position = fixed.css("position"); var offsetTop = fixed.offset().top; //定义滚动事件,判断scrollTop及offsetTop $(window).scroll(function () { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop > offsetTop) { fixed.css({ "position": "fixed", "width": "100%", "top": "0" }); } else { //移除style属性并赋予css fixed.removeAttr("style").css({ "position": position, "width": "100%" }); } }); }) </script>