scroll-view 组件里的 scroll-into-view 属性实例
微信小程序的scroll-view组件中,scroll-into-view 属性可以指定滚动到指定id的位置。
<scroll-view class="content" scroll-y scroll-into-view="{{ intoIndex }}" scroll-with-animation>
intoIndex 值应为某子元素id(id不能以数字开头),设置哪个方向可滚动,则在哪个方向滚动到该元素。scroll-y 是滑动方向。
下面写个简单的小实例,方便大家理解。
wxml:
<view class="box"> <scroll-view class="nav" scroll-y> <view class="item {{indexId == index ? 'current' : ''}}" wx:for="{{navList}}" bindtap="scrollClick" data-id="{{index}}">{{index}}-{{item}}</view> </scroll-view> <scroll-view class="content" scroll-y scroll-into-view="{{intoIndex}}" scroll-with-animation> <view wx:for="{{contentList}}" id="item{{index}}">{{index}}-{{item}}</view> </scroll-view> </view>
css:
.nav { margin-top:100rpx; width: 20%; height: 100vh; background: pink; text-align: center; } .nav .item { height: 100rpx; line-height: 100rpx; border-bottom: 1px solid #ebebeb; background: #fafafa; } .nav .current{ color:red; } .content { width: 75%; height: 100%; position: absolute; right: 0px; top: 55px; margin: 0 20rpx 0 20rpx; box-sizing: border-box; } .content view { height: 200rpx; line-height: 200rpx; border: 1px solid #ccc; border-radius: 20rpx; margin-top: 20rpx; text-align: center; }
js:
Page({ /** * 页面的测试数据 */ data: { navList: ["饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料","饮料"], contentList: ["可乐", "雪碧", "芬达", "七喜", "冰红茶", "冰绿茶", "茉莉花茶", "柠檬茶", "果粒橙", "茉莉蜜茶", "柠檬红茶", "脉动", "红牛", "酸梅汤", "北冰洋", "九龙斋", "王老吉", "沙棘汁", "鲜橙多", "元气森林", "健力宝", "加多宝", "东方树叶", "乌龙茶", "茉莉绿茶", "宝矿力", "拿铁咖啡", "摩卡咖啡", "生椰拿铁", "冰吸生椰", "美式咖啡", "焦糖玛奇朵", "燕麦拿铁", "丝绒拿铁", "香草拿铁", "榛果拿铁", "卡布奇诺", "冷萃咖啡", "海盐焦糖", "绵云拿铁", "生酪拿铁", "厚乳拿铁", "抹茶燕麦拿铁", "珍珠奶茶", "鲜百香双响炮", "奶茶三兄弟", "椰果奶茶", "鲜百香双响炮", "金钻奶茶", "珍珠奶茶", "布丁奶茶", "奶茶三兄弟", "双拼奶茶", "鲜百香双响炮", "奶茶三兄弟", "烧仙草奶茶", "鲜百香双响炮", "红豆奶茶", "珍珠奶茶", "巧克力奶茶", "奶茶三兄弟"], intoIndex: '', indexId: 0 }, scrollClick: function (e) { this.setData({ intoIndex: "item" + e.currentTarget.dataset.id, indexId: e.currentTarget.dataset.id }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
效果图: