uni-app中滑动到最右侧scrollLeft为啥和scrollWidth的值不一样?
uni-app中滑动到最右侧scrollLeft为啥和scrollWidth的值不一样?
通过 uni.createSelectorQuery()
scrollOffset方法拿到了 scroll-view组件的可滚动的大小(ScrollWidth)
然后我监听这个 组件的@scroll事件,拿到 事件对象中的 scrollLeft,
当我滑动到最右侧,这个 scrollLeft 和 ScrollWidth 相差 100-200的数值…
1 回复
更多关于uni-app中滑动到最右侧scrollLeft为啥和scrollWidth的值不一样?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在uni-app的scroll-view组件中,scrollLeft和scrollWidth值不一致是正常现象,主要原因是:
1. 计算基准不同
scrollWidth是scroll-view内容区域的总宽度scrollLeft是可视区域左侧到内容区域左侧的距离
2. 可视区域的影响
当滑动到最右侧时,scrollLeft的最大值应该是:
scrollLeft_max = scrollWidth - clientWidth
其中clientWidth是scroll-view可视区域的宽度。
3. 获取准确值的方法
// 获取完整信息
uni.createSelectorQuery()
.select('#scrollView')
.fields({
scrollOffset: true,
size: true
}, (res) => {
// res.scrollWidth 内容总宽度
// res.width 可视区域宽度
// res.scrollLeft 当前滚动位置
const maxScrollLeft = res.scrollWidth - res.width
console.log('最大可滚动值:', maxScrollLeft)
}).exec()
4. 判断是否滚动到底部
// 在[@scroll](/user/scroll)事件中
handleScroll(e) {
const scrollLeft = e.detail.scrollLeft
const scrollWidth = e.detail.scrollWidth
const clientWidth = this.scrollWidth // 需要提前获取可视宽度
// 允许1px的误差
const isEnd = Math.abs(scrollLeft - (scrollWidth - clientWidth)) <= 1
}

