您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

关于JavaScript如何实现导航栏吸顶操作的实例分享

2025/8/9 23:51:49发布25次查看
关于javascript如何实现导航栏吸顶操作的实例分享
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <style type="text/css"> body { padding:0; margin:0; } #nav { width:100%; height:60px; background:#39f; color:#fff; line-height:60px; text-align:center; padding:0; margin:0; list-style:none; } #nav li { float:left; width:20%; height:60px; } .fix { position:fixed; top:0; left:0; } </style> </head> <div class="wrap"> <h1>在线书城</h1> <p>有没有一本书让你仿佛遇到春风十里</p> <ul id="nav"> <li>加入购物车</li> <li>加入收藏</li> <li>立即购买</li> </ul> <div class="con"> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> <p>好书有好事有好诗</p> </div> </div> <script type="text/javascript"> var tit = document.getelementbyid("nav"); //alert(tit); //占位符的位置 var rect = tit.getboundingclientrect();//获得页面中导航条相对于浏览器视窗的位置 var inser = document.createelement("div"); tit.parentnode.replacechild(inser,tit); inser.appendchild(tit); inser.style.height = rect.height + "px"; //获取距离页面顶端的距离 var titletop = tit.offsettop; //滚动事件 document.onscroll = function(){ //获取当前滚动的距离 var btop = document.body.scrolltop||document.documentelement.scrolltop; //如果滚动距离大于导航条据顶部的距离 if(btop>titletop){ //为导航条设置fix tit.classname = "clearfix fix"; }else{ //移除fixed tit.classname = "clearfix"; } } </script> </html>
当页面向下滚动时超过了吸顶导航的初始位置时,需要把吸顶导航栏固定在窗口顶部,一般吸顶导航栏还可以替换成文章标题栏,搜索框、tab条等等,例如百度糯米,天猫,淘宝最为常用。它们共同点是在内容或者功能上比较重要,但又不是最重要的元素,最重要的一般会放置于顶部。
1.实现思路是监听 scroll 事件,判断当前页面的滚动位置,当滚动距离大于导航条距顶部的距离时,为导航条采用窗口定位。
2.与“回到顶部“的实现方法一样,但是会发现实现吸顶功能时,到了临界位置时,页面会抖动一下,因为当导航条fixed出去,下部内容填补了导航条离开的位置。抢占了导航条的位置,所以抖动了一下。此处我们设置一个占位符,守住导航条的位置。
效果如下:
以上就是关于javascript如何实现导航栏吸顶操作的实例分享的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product