導航欄滾動到頂部時固定在頂部

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 });
		}
	}
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章