前端滚动组件分享
分享一个前端可视化常用的卡片列表滚动组件,常用于可视化项目左右两侧的卡片列表的滚动。效果如下图所示:
组件描述
- 当鼠标移入滚动区域时,滚动行为停止当鼠标再次离开时,滚动继续
源码展示
<template>
<div ref="moocBox" class="custom-scroll-content" @mouseout="mouseOut" @mouseover="mouseOver">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'CustomScroll',
data() {
return {
speed: 50,
myScroll: null
};
},
created() {
},
mounted() {
this.myScroll = setInterval(() => {
this.scrollUp();
}, this.speed);
},
destroyed() {
clearInterval(this.myScroll);
// removeEventListener("scroll", this.myScroll);
},
beforeDestoryed() {
clearInterval(this.myScroll);
this.myScroll = null
},
methods: {
/**
* @description: 滚动
* @return void 滚动
*/
scrollUp() {
this.$refs.moocBox.scrollTop += 1;
// 判断滚动条是否到底
if (this.$refs.moocBox.scrollTop + this.$refs.moocBox.clientHeight >= this.$refs.moocBox.scrollHeight) {
this.$refs.moocBox.scrollTop = 0;
}
},
/**
* @description: 鼠标滑过暂停滚动
* @return void 清除定时器,实现暂停
*/
mouseOver() {
clearInterval(this.myScroll);
},
/**
* @description: 鼠标移开重新滚动
* @return void 设定定时器,实现滚动
*/
mouseOut() {
this.myScroll = setInterval(() => {
this.scrollUp();
}, this.speed);
},
}
};
</script>
<style>
.custom-scroll-content {
height: 100%;
overflow: auto;
}
</style>
使用指南
<template>
<div class="home">
<div class="container__div_height-500">
<CustomScroll>
<div class="item__div_height-100" v-for="i in 10" :key="i">{{ i+1 }}</div>
</CustomScroll>
</div>
</div>
</template>
import CustomScroll from '../components/customScroll.vue';
export default {
name: 'Home',
components: {
CustomScroll,
},
}
</script>
<style>
.home {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.container__div_height-500 {
height: 500px;
width: 400px;
}
.item__div_height-100 {
height: 100px;
width: 100%;
background-color: pink;
margin-bottom: 12px;
cursor: pointer;
}
.item__div_height-100:last-child {
margin-bottom: 0;
}
::-webkit-scrollbar {
width: 0!important;
}
</style>
属性说明
属性 | 属性值 | 类型 |
---|---|---|
speed | 设置滚动速度,默认50 | Number |