1. 如何使用scroll-view实现横向滚动?
<scroll-view
class="mml-nav-scroll"
scroll-x="true">
<view id="mml_nav1" class="mml-scroll-item active">热销</view>
<view id="mml_nav2" class="mml-scroll-item">现货</view>
<view id="mml_nav3" class="mml-scroll-item">酒饮</view>
<view id="mml_nav4" class="mml-scroll-item">美护</view>
<view id="mml_nav5" class="mml-scroll-item">餐厨</view>
<view id="mml_nav6" class="mml-scroll-item">出行</view>
<view id="mml_nav7" class="mml-scroll-item">服装</view>
<view id="mml_nav8" class="mml-scroll-item">数码</view>
</scroll-view>
white-space: nowrap
必须设置不换行,否则不能滚动
.mml-scroll-item { width: 20%; height: 100%; line-height: 140rpx; display: inline-block; text-align: center; }
子元素必须设置固定的宽度,和设置内联
.mml-nav-scroll {
width: 100%;
white-space: nowrap;
height: 140rpx;
}
.mml-scroll-item {
width: 20%;
height: 100%;
line-height: 140rpx;
display: inline-block;
text-align: center;
}
.mml-scroll-item.active {
color: #eb544d;
font-size: 24px;
font-weight: 800;
}
2. 点击添加类名
<scroll-view
class="mml-nav-scroll"
scroll-x="true">
<view wx:key="index" wx:for="{{navList}}"
bindtap="navAction" id="mml_nav_{{index}}"
class="{{num == index?'mml-scroll-item active':'mml-scroll-item'}}">{{item}}</view>
</scroll-view>
点击设置num添加类名 num的值等于下标的时候添加active类名
data: {
num: 0,
navList: ['热销', '酒饮',
'美护', '餐厨', '出行',
'服装' ,'数码']
},
//事件处理函数
navAction (e) {
let num = e.target.id.charAt(e.target.id.length-1)
this.setData({
num: num
})
}