1. 程式人生 > >微信小程式如何讓導航隨著滾動替換內容

微信小程式如何讓導航隨著滾動替換內容

nav.xml

-------------------------------------------------------------------------------------------------------------

<!--pages/nav/nav.wxml-->

<view class='nav-container'>

<view class='navTitle'>{{navTitle}}</view>

<scroll-view scroll-y style="height: 1500rpx" bindscroll="scroll" scroll-into-view="{{toView}}" scroll-top="{{scrollTop}}">

<view class='navBox'>

<view class='title'>{{title1}}</view>

<view class='title titleRed'>{{title2}}</view>

<view class='title titleOrange'>{{title3}}</view>

<view class='titleBottom'></view>

</view>

</scroll-view>

</view>

 

-------------------------------------------------------------------------------------------------------------

nav.wxss

-------------------------------------------------------------------------------------------------------------

.navTitle{width:100%;height:50px;background:#ccc;line-height:50px;padding-left:30rpx;color:green;position:fixed;top:0;z-index: 10;}

.title{height:1000rpx;background:green;padding-left:30rpx;margin-top:60px;}

.titleBottom{height:100rpx;}

.titleRed{background:red;}

.titleOrange{background:orange;}

.titlePink{background:pink;}

-------------------------------------------------------------------------------------------------------------

nav.js

-------------------------------------------------------------------------------------------------------------

Page({

 

/**

* 頁面的初始資料

*/

data: {

toView: 'red',

scrollTop: 0,

navTitle: "導航",

title1: "標題1",

title2: "標題2",

title3: "標題3"

},

 

/**

* 生命週期函式--監聽頁面載入

*/

onLoad: function (options) {

},

scroll: function (e) {

// console.log(e)

// console.log(e.detail.scrollTop);

const scrollTop = e.detail.scrollTop;

var query = wx.createSelectorQuery();//建立選擇器

var that = this;

console.log("滾動值:" + scrollTop);

query.selectAll('.title').boundingClientRect(function (rect) {

rect[0].title = "標題1"

rect[1].title = "標題2"

rect[2].title = "標題3"

// var title1 = rect[0].top;

rect[1].top = rect[1].top + 400;

rect[2].top = rect[2].top + 760;//可以調整

for(var i = 0; i < rect.length; i++)

{

if(scrollTop >= rect[i].top)

{

that.setData({

navTitle: rect[i].title

})

}

}

}).exec();

 

},

/**

* 生命週期函式--監聽頁面初次渲染完成

*/

onReady: function () {

},

 

/**

* 生命週期函式--監聽頁面顯示

*/

onShow: function () {

},

 

/**

* 生命週期函式--監聽頁面隱藏

*/

onHide: function () {

},

 

/**

* 生命週期函式--監聽頁面解除安裝

*/

onUnload: function () {

},

 

/**

* 頁面相關事件處理函式--監聽使用者下拉動作

*/

onPullDownRefresh: function () {

},

 

/**

* 頁面上拉觸底事件的處理函式

*/

onReachBottom: function () {

},

 

/**

* 使用者點選右上角分享

*/

onShareAppMessage: function () {

}

})