导航栏滚动到顶部时固定在顶部

文章目录

HTML

	<div class="top"></div>
	<div id="fixed"></div>

	*{margin: 0;padding: 0;}
	body{height: 1000px;}
	.top{
		width: 100%;
		height: 200px;
		background: blue;
	}
	#fixed{
		width: 100%;
		height: 50px;
		background: #000;
		top: 0;
	}
	.top-nav{position: fixed;}
	
	$(window).scroll(function(){
		//$(document).scrollTop()获取垂直滚动的距离 即当前滚动的地方的窗口顶端到整个页面顶端的距离
		//$(window).height()是获取当前浏览器所能看到的页面的那部分的高度,这个大小在你缩放浏览器窗口大小时会改变
		var $document = $(document).scrollTop()
		if($document > 200 && $document < $(window).height()){
			$("#fixed").addClass("top-nav");
		}else if($document < 200 && $document){
			$("#fixed").removeClass("top-nav")
		}
	})

小程序吸顶

<!--index.wxml-->
<view class="container">
  <view id="scroll-list1" class="topBox {{isAllow?'fixed-scroll-list':''}}" style="top:{{isAllow?0:''}}px">
  	<view class="scroll-list flex-atw">
  		<view class="list-name {{ index == scrollIndex ? 'is-name':''}}" wx:for="{{shopCategoryList}}" wx:key="{{index}}">
  			<view class="item-name">{{item.name}}</view>
  			<view wx:if="{{index == scrollIndex}}" class='btn-line'></view>
  		</view>
  	</view>
  </view>
</view>
<!--js-->
Page({
	data: {
		isAllow: false, // 是否运行滚动
		bartop: 20,//导航栏距离顶部距离
		shopCategoryList: [
		{name: '标题1'},
		{name: '标题2',},
		{name: '标题3',},
		],
	},
	onLoad: function() {
       this.getHeigt()
	},
	getHeigt() {
	//获取导航栏距离顶部距离
		let that = this;
		let query = wx.createSelectorQuery();
		query.selectAll('#scroll-list1').boundingClientRect(function(rect) {}).exec(function(res) {
			// 加载失败时重新获取高度
			if (!res[0][0]) {
				setTimeout(() => {
					that.getHeigt()
				}, 500)
				return
			}
			let bartop = res[0][0]['top']; // 顶部bar距离顶部的距离
			wx.getSystemInfo({
				success: function(res) {
					that.setData({
						bartop: bartop
					})
				}
			})
		});
	},
	// 监听页面滚动
	onPageScroll(e) {
		let scrollTop = e.scrollTop;
		//tab置顶
		if (scrollTop >= this.data.bartop) {
			if (this.data.isAllow) { return; }
			this.setData({ isAllow: true });
		} else {
			if (!this.data.isAllow) { return; }
			this.setData({ isAllow: false });
		}
	}
})
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值