vue 自定义元素自动滚动鼠标移入停止移出滚动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/vant@2.12/lib/index.css" />
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<title></title>
<style>
.scroll-container {
width: 300px; /* 根据需要设置宽度 */
overflow: hidden; /* 隐藏溢出内容 */
border: 1px solid #ccc; /* 可选:添加边框 */
position: relative; /* 用于定位内部内容 */
}
.scroll-content {
overflow-y: scroll; /* 启用垂直滚动 */
height: 100%; /* 使内容区域填满容器 */
}
.scroll-item {
height: 50px; /* 根据需要设置项的高度 */
border-bottom: 1px solid #eee; /* 可选:添加分隔线 */
padding: 10px; /* 可选:添加内边距 */
box-sizing: border-box; /* 包含内边距和边框在高度内 */
}
</style>
</head>
<body>
<div id="app">
<div class="scroll-container" ref="scrollContainer" :style="{'height':height +'px'}" @mouseenter="pauseScroll" @mouseleave="resumeScroll">
<div class="scroll-content" ref="scrollContent">
<!-- 假设这里有很多内容需要滚动 -->
<div v-for="(item, index) in items" :key="index" class="scroll-item">{{ item }}</div>
</div>
</div>
</div>
</body>
<script src="https://unpkg.com/vue@2.6/dist/vue.min.js"></script>
<script src="https://unpkg.com/vant@2.12/lib/vant.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<!--组件-->
<script>
var vm = new Vue({
el: '#app',
data() {
return {
items: Array.from({ length: 5 }, (_, i) => `Item ${i + 1}`), // 生成20个项作为示例内容
scrollStep: 2, // 每次滚动的像素数
scrollInterval: null, // 定时器ID
isScrolling: false, // 是否正在滚动
height:100
}
},
mounted() {
this.startAutoScroll();
},
beforeDestroy() {
this.stopAutoScroll();
},
methods: {
startAutoScroll() {
this.scrollInterval = setInterval(this.scroll, 100); // 每100毫秒检查一次是否需要滚动
},
// 销毁定时器
stopAutoScroll() {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
},
// 鼠标移入时暂停滚动
pauseScroll() {
this.stopAutoScroll();
},
// 鼠标移出时恢复滚动
resumeScroll() {
this.startAutoScroll();
},
// 滚动内容
scroll() {
if (this.isScrolling) return; // 防止重复触发滚动
const content = this.$refs.scrollContent;
const scrollTop = content.scrollTop;
const scrollHeight = content.scrollHeight;
const clientHeight = this.$refs.scrollContainer.clientHeight;
console.log(clientHeight,"clientHeight")
// 计算下一个滚动位置
let nextScrollTop = scrollTop + this.scrollStep;
// 检查是否到达底部
if (nextScrollTop >= scrollHeight - clientHeight) {
nextScrollTop = 0; // 重置到顶部
}
// 应用新的滚动位置
content.scrollTop = nextScrollTop;
// 如果滚动位置发生了变化,则标记为正在滚动(防止重复触发)
if (scrollTop !== nextScrollTop) {
this.isScrolling = true;
// 在下一个事件循环中取消标记(使用 setTimeout 实现异步)
setTimeout(() => {
this.isScrolling = false;
}, 0);
}
},
}
}
)
</script>
</html>
注:简化开发,方便粘贴