<template>
<div class="app-wrapper">
<!-- 文本超出,左右按钮滚动 -->
<div id="click-scroll-X">
<span class="left_btn" @click="leftSlide">《</span>
<div class="scroll_wrapper" ref="wrapperCon">
<div class="scroll_list">
<div class="item" v-for="(item, index) in classify" :key="index">
{{ item.encoded }}
</div>
</div>
</div>
<div class="right_btn" @click="rightSlide">》</div>
</div>
</div>
</template>
<script>
export default ({
name: '',
components: {},
props: {},
data() {
return {
timer: null, // 定时器(方便清除)
classify: [
{ encoded: 'TJ202209A10' },
{ encoded: 'TJ202209A11' },
{ encoded: 'TJ202209A12' },
{ encoded: 'TJ202209A13' },
{ encoded: 'TJ202209A14' },
{ encoded: 'TJ202209A15' },
{ encoded: 'TJ202209A16' },
{ encoded: 'TJ202209A17' },
{ encoded: 'TJ202209A18' },
{ encoded: 'TJ202209A19' },
{ encoded: 'TJ202209A20' }
]
}
},
created() { },
methods: {
// 左箭头
leftSlide() {
// 保存滚动盒子左侧已滚动的距离
let left = this.$refs.wrapperCon.scrollLeft
let num = 0
clearInterval(this.timer)
this.timer = null
this.timer = setInterval(() => {
// !left:已经滚动到最左侧
// 一次性滚动距离(可调节)
if (!left || num >= 300) {
// 停止滚动
clearInterval(this.timer)
this.timer = null
return
}
// 给滚动盒子元素赋值向左滚动距离
this.$refs.wrapperCon.scrollLeft = left -= 30
// 保存向左滚动距离(方便判断一次性滚动多少距离)
num += 30
}, 20)
// 20:速度(可调节)
},
// 右箭头
rightSlide() {
// 保存滚动盒子左侧已滚动的距离
let left = this.$refs.wrapperCon.scrollLeft
// 保存元素的整体宽度
let scrollWidth = this.$refs.wrapperCon.scrollWidth
// 保存元素的可见宽度
let clientWidth = this.$refs.wrapperCon.clientWidth
let num = 0
clearInterval(this.timer)
this.timer = setInterval(() => {
// 已经滚动距离+可见宽度
// left+clientWidth>=scrollWidth:滚动到最右侧
// num>=300一次性滚动距离
if (left + clientWidth >= scrollWidth || num >= 300) {
clearInterval(this.timer)
return
}
// 给滚动盒子元素赋值向左滚动距离
this.$refs.wrapperCon.scrollLeft = left += 30
// 保存向左滚动距离(方便判断一次性滚动多少距离)
num += 30
}, 20)
// 20:速度(可调节)
}
},
})
</script>
<style lang='scss' scoped>
#click-scroll-X {
display: flex;
align-items: center;
.left_btn,
.right_btn {
font-size: 30px;
cursor: pointer;
margin: -10px -5px 0;
}
.scroll_wrapper {
width: 600px;
overflow-x: scroll;
padding-bottom: 10px;
.scroll_list {
display: flex;
align-items: center;
justify-content: space-between;
.item {
cursor: pointer;
width: 146px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ccc;
border-radius: 3px;
box-sizing: border-box;
flex-shrink: 0;
margin: 0 2px;
}
}
}
}
/*隐藏滚动条*/
.scroll_wrapper::-webkit-scrollbar {
display: none;
}
</style>
vue实现点击按钮左右滚动
最新推荐文章于 2023-12-21 16:17:20 发布