以微信小程序为例
wxml
<scroll-view
class="scroll-menu"
scroll-left="{{scrollLeft}}"
scroll-x="{{true}}"
scroll-with-animation="{{true}}"
enable-flex="{{true}}">
<view
class="menu-item {{selectedIndex === index && 'activeMenu'}}"
wx:for="{{menuList}}"
wx:key="index"
data-index="{{index}}"
bindtap="handleTap">
{{item.name}}
</view>
</scroll-view>
js
Page({
data: {
menuList: [
{ name: "全部分类" },
{ name: "拼团" },
{ name: "限时" },
{ name: "新人" },
{ name: "爆品" },
{ name: "日用品" },
{ name: "床上用品" },
{ name: "水果类" },
],
selectedIndex: 0,
scrollLeft: 0,
menuWidth: 0,
menuItemArr: [],
},
onReady: function () {
let _this = this;
const queryDom = wx.createSelectorQuery().in(_this);
queryDom
.select(".scroll-menu")
.boundingClientRect()
.exec(function(res) {
console.log(res);
_this.setData({
menuWidth: res[0].width
});
});
let arr = [];
queryDom
.selectAll(".menu-item")
.boundingClientRect()
.exec(function(res) {
console.log(res);
res[1].forEach(item => {
arr.push({ width: item.width, left: item.left });
});
_this.setData({
menuItemArr: arr
});
});
console.log(_this.data.menuWidth, _this.data.menuItemArr);
},
handleTap(e) {
let selectedIndex = e.target.dataset.index;
let selectedItem = this.data.menuItemArr[selectedIndex];
if (selectedItem) {
let targetDistance = selectedItem.left - (this.data.menuWidth - selectedItem.width) / 2;
targetDistance = targetDistance < 0 ? 0 : targetDistance;
this.setData({
scrollLeft: targetDistance,
selectedIndex
});
}
}
})
wxss
.scroll-menu {
width: 100%;
height: 40px;
display: flex;
flex-wrap: nowrap;
border-bottom: 2rpx solid #eee;
padding: 0 20rpx;
box-sizing: border-box;
}
.menu-item {
white-space: nowrap;
display: flex;
align-items: center;
margin-right: 40rpx;
}
.activeMenu {
color: red;
}
效果图
