• JS实现菜单滚动到一定高度后固定


    在有些网页中我们会发现会有这样的现象:某个div会随着屏幕的滚动达到一定高度的时候位置就固定下来了。例如一下导航条:

    那么这里就需要用到JS的逻辑方法来实现了。

    html

    <div id="space"></div>
    <ul id="nav"> 
       <li><a href="#content1">美食</a></li> 
       <li><a href="#content2">娱乐</a></li> 
       <li><a href="#content3">超市</a></li> 
       <li><a href="#content4">出行</a></li> 
       <li><a href="#content5">养车</a></li> 
    </ul> 
    <div id="content1">内容区域一</div>
    <div id="content2">内容区域二</div>
    <div id="content3">内容区域三</div>
    <div id="content4">内容区域四</div>
    <div id="content5">内容区域五</div>
    

    js

    <script type="text/javascript">
    	window.onscroll=function(){
    	    var topScroll =document.body.scrollTop || document.documentElement.scrollTop;//滚动的距离,距离顶部的距离
    		console.log(topScroll,'topScroll')
    		var space  = document.getElementById("space");
    		var bignav  = document.getElementById("nav");//获取到导航栏id
    		var spaceOffsetHeight = space.offsetTop    //以spce的滚动高度为参照
    		console.log(spaceOffsetHeight,'navOffsetHeight')
    		if(topScroll > spaceOffsetHeight){  
    			bignav.style.position = 'fixed';
    			bignav.style.top = '0';
    			bignav.style.zIndex = '9999';
    		} else {
    			bignav.style.position = 'static';
    		}
    	}
    </script>
    
  • 相关阅读:
    linux异常处理体系结构
    网站、架构、集群相关资源
    (转)分布式Web服务器架构的演变与技术需求
    B树、B树、B+树、B*树详解(转)
    (转)事件和路由事件概述
    LCID及Culture Name列表
    触摸键盘概述
    MySQL远端连接设置
    C#实现平衡多路查找树(B树) (转)
    CentOS6.3 LAMP运营环境安装
  • 原文地址:https://www.cnblogs.com/wangRong-smile/p/11981179.html
Copyright © 2020-2023  润新知