wxml部分,结构很简单
<view class='block' style='height:1050rpx;width:100%;'></view>
<view wx:for='{{list}}' wx:key='{{index}}' class='item item-{{index}}'>
<image class='img {{item.show ? "active":""}}' src='{{item.show ? item.src:item.def}}'></image>
</view>
</view>
循环的list是要生成的图片的数组,这里通过设置数组的show属性来判断是否显示图片。ps:这里用的随机生成的数据,默认显示的是一张gif图。
list: [{
src: 'http://lorempixel.com/640/480/nightlife',
show: false,
def: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545818293982&di=930d3ef0da6fac27814725dcce73693b&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0195f55972f18ca8012193a342310a.gif'
}, {
src: 'http://lorempixel.com/640/480/fashion',
show: false,
def: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545818293982&di=930d3ef0da6fac27814725dcce73693b&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0195f55972f18ca8012193a342310a.gif'
}, {
src: 'http://lorempixel.com/640/480/animals',
show: false,
def: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545818293982&di=930d3ef0da6fac27814725dcce73693b&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0195f55972f18ca8012193a342310a.gif'
}, {
src: 'http://lorempixel.com/640/480/people',
show: false,
def: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545818293982&di=930d3ef0da6fac27814725dcce73693b&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0195f55972f18ca8012193a342310a.gif'
}
]
},
js重点部分:调用api wx.createIntersectionObserver().relativeToViewPort() 绑定监听事件 根据返回的ret.intersectionRatio > 0 来判断是否出现在视界里,让它显示。
// this.showImg();
let list = this.data.list;
for (let i in list) {
wx.createIntersectionObserver().relativeToViewport().observe('.item-' + i, (ret) => {
if (ret.intersectionRatio > 0) {
list[i].show = true
}
})
}
this.setData({
list
})
}```
网友评论