使用微信提供的IntersectionObserver
对象
IntersectionObserver
对象,用于推断某些节点是否可以被用户看见、有多大比例可以被用户看见.
在页面渲染开始时,通过这个api指明需要监听的元素,系统会自动去监听元素位置
let data = list;<view wx:for="{{data}}" wx:for-item="item"><img class="img-{{index}}" src="{{item.imgShow? item.src: ''}}" class="{{item.showState?'opacity-100':''}}"></img></view>data.forEach((item,index)=>{this.createIntersectionObserver().relativeToViewport.observe(`.img-${index}`,res=>{if (res.intersectionRatio > 0){this.setData({item.imgShow:true})}})}).opacity-100 {opacity: 1}
intersectionRatio
值大于0,说明元素出现在可视范围