vue中利用iscroll.js解决pc端滚动问题

2020-06-16 06:52:25易采站长站整理

this.myScroll.scrollTo(0, y)
},
<!--获取实例-->
getIscroll (iscroll) {
this.myScroll = iscroll
}
}
}
</script>
<style scoped>
<!--样式-->
...
</style>

这里面用到的都是 iscroll 插件自带的属性和方法进行滚动边界的判断和滚动,比用 JavaScript 方法方便的多,而且用了iscroll作为滚动容器,已经在vIscroll.js禁用了相关浏览器默认事件。

3-2、居中显示

这里 JavaScript 有个 scrollIntoView() 方法, 官方文档链接 ,这个方法让当前的元素滚动到浏览器窗口的可视区域内。关键缺点是,如果横向滚动和竖向滚动都同时用到这个方法,只能保证一个滚动区域有效,另一个会不滚动。

使用 scrollIntoView() 方法配置如下:


this.$refs.tabItem[this.currentIndex].scrollIntoView({
behavior: "smooth",
inline: "center",
block: 'nearest'
})

这里在横向滚动区域添加了一对左右按钮,实现切换功能,如图所示:

切换按钮示例图

切换按钮事件方法就是通过改变上一个、下一个按钮下标,调用方法,实现切换功能,切换事件方法逻辑如下:


tabBtnEvent (direction) {
const max = this.$refs.tabItem.length
if (direction === 'left' && this.currentIndex > 0) {
this.currentIndex--
}
if (direction === 'right' && this.currentIndex < max - 1) {
this.currentIndex++
}
<!--调用单击按钮事件-->
this.tabEvent(this.$refs.tabItem[this.currentIndex], this.currentIndex)
},

下面对 单击按钮事件 添加居中逻辑,详细代码和解析图如下,可以对比查看:

居中计算图


tabEvent (item, currentIndex) {
this.currentId = item.id
this.currentIndex = currentIndex
// 获取滚动容器的长度的一半,即中间点
const scrollContainerHalfWidth = this.$refs.scrollContainer.offsetWidth / 2
// 获取单个item的一半长度
const tabItemHalfWidth = this.$refs.tabItem[currentIndex].offsetWidth / 2
// 求取插值,就是开始到中间开始位置的距离
const halfDistance = scrollContainerHalfWidth - tabItemHalfWidth
// 求取当前item的相对总长度的偏移量
const currentItemOffsetLeft = this.$refs.tabItem[currentIndex].offsetLeft
// scroll 移动到中间的值
const x = halfDistance - currentItemOffsetLeft
this.myScroll.scrollTo(x, 0)