欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > vue3+TS 手动实现表格滚动

vue3+TS 手动实现表格滚动

2025/4/28 22:57:12 来源:https://blog.csdn.net/qq_39748755/article/details/147480466  浏览:    关键词:vue3+TS 手动实现表格滚动

第一步定义变量

  // 定义滚动定时器

  const scrollInterval = ref<number | null>(null)

  // 定义是否悬浮

  const isHovered = ref(false)

  // 定义初始化定时器

  const initTimer = ref<number | null>(null)

  // 定义底部暂停定时器

  const bottomPauseTimer = ref<number | null>(null)

  // 定义是否滚动到底部

  const isAtBottom = ref(false)

  // 是否滚动中

  const isScrolling = ref(false)

第二部再html部分撰写内容

<divclass="content-box"ref="contentBoxRef"@mouseenter="isHovered = true"@mouseleave="isHovered = false"><div v-for="(item, index) in props.dataList" :key="index" class="content-item"><template v-for="(row, number) in props.headerList" :key="row.key"><div class="row-item" :style="getRowItemStyle(row)"><img v-if="!number" class="ranking-item" :src="getImg(index)" alt="排位" /><span class="ellipsis-text">{{ item[row.key] }}</span></div></template></div></div>

第三步进行js代码部分撰写

/*** @description: 启动自动滚动* @return {void}*/const startAutoScroll = () => {if (scrollInterval.value || isScrolling.value) return// 初始延迟5秒isScrolling.value = falseinitTimer.value = window.setTimeout(() => {isScrolling.value = truedoScroll()}, 3000)}/*** @description: 执行滚动* @return {void}*/const doScroll = () => {if (scrollInterval.value) returnscrollInterval.value = window.setInterval(() => {if (!contentBoxRef.value || isHovered.value || !isScrolling.value) returnconst { scrollTop, scrollHeight, clientHeight } = contentBoxRef.valueconst canScroll = scrollHeight > clientHeightconst reachedBottom = scrollTop + clientHeight >= scrollHeight - 1if (canScroll) {if (reachedBottom && !isAtBottom.value) {// 到达底部,暂停5秒isAtBottom.value = trueisScrolling.value = falseif (scrollInterval.value) clearInterval(scrollInterval.value)scrollInterval.value = nullbottomPauseTimer.value = window.setTimeout(() => {// 暂停结束后回到顶部contentBoxRef.value!.scrollTop = 0isAtBottom.value = falseisScrolling.value = falsestartAutoScroll() // 重新开始滚动}, 3000)} else if (!reachedBottom) {// 正常滚动contentBoxRef.value.scrollBy({top: 1,behavior: 'smooth',})}}}, 50) as unknown as number}/*** @description: 停止所有滚动和定时器* @return {void}*/const stopAllScroll = () => {if (initTimer.value) {clearTimeout(initTimer.value)initTimer.value = null}if (bottomPauseTimer.value) {clearTimeout(bottomPauseTimer.value)bottomPauseTimer.value = null}if (scrollInterval.value) {clearInterval(scrollInterval.value)scrollInterval.value = null}isScrolling.value = falseisAtBottom.value = false}// 调用接口之后删除onMounted(() => {// 启动自动滚动(会有初始5秒延迟)startAutoScroll()})onUnmounted(() => {// 组件卸载时清除所有定时器stopAllScroll()})

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词