微信小程序scroll-view锚链接跳转
效果:
wxml代码(直接给大家上代码吧,没有太复杂的逻辑)
<view class="container">
<scroll-view class="content" scroll-into-view="{{toView}}" scroll-y="true" scroll-with-animation="true">
<view wx:for='{{act_addList}}'>
<view style='color:red' class='flop' data-pid="{{item.region}}" id="{{'toView'+item.region}}">{{item.region}}</view>
<view wx:for='{{item.keys}}' >{{item.keyword}}</view>
</view>
<view></view>
</scroll-view>
<view class='orientation_region'>
<view wx:for='{{act_addList}}' data-index='{{index}}' data-id="{{item.region}}" bindtap='scrollToViewFn'>
{{item.region}}</view>
</view>
</view>
js代码
//index.js
//获取应用实例
const utils = require('../../utils/util.js')
const app = getApp()
Page({
data: {
act_addList:[],
orientationList:[],
toView: ''
},
onLoad: function() {
this.loadList()
},
//初始化数据
loadList() {
let param = new Object()
let act_addList = this.data.act_addList,
orientationList = this.data.orientationList
param.organid = 14
utils.showLonding('加载中', true)
app.net.$Api.getdiseaselistList(param).then((res) => {
for (let i in res.data.data){
//这里要处理一下数据
act_addList.push({
region: i,
keys: res.data.data[i],
})
}
this.setData({
act_addList: act_addList,
},()=>{
utils.hideLonding();
})
console.log(this.data.act_addList)
})
},
//锚链接点击事件
scrollToViewFn: function (e) {
let id = e.target.dataset.id;
this.setData({
toView: 'toView' + id, //toViewG
});
console.log(this.data.toView)
},
})
css样式(一定要设置高度 不然没有滚动效果)
/**index.wxss**/
.container{
height: 100vh;
display: flex;
}
.content {
width: 100%;
height: 86%; /*一定要设置高度*/
position: relative;
padding-bottom: 40rpx;
box-sizing: border-box;
background: #f8f8f8;
}
.orientation_region{
position: fixed;
top: 10rpx;
right: 10rpx;
}
数据结构展示一下
基本上就是这样,大家自己吸收一下,scroll-into-view="{{toView}}" 跟 元素id一样即可。