需求 等用户读一会儿,如果有文字没展示全,自动往上滚动,滚动到底部大概一两秒再回到顶部。
备注:具体情况多调试一会儿,保证没问题,逻辑很好理解,耐心
dom
<div ref="scroll-box" class="scroll-box">
<div ref="content" class="content">{{ detailsData.content }}</div>
</div>
逻辑
async scrollText() {
clearInterval(this.scrollInterval)
await this.$nextTick()
const contentHeight = this.$refs.content.clientHeight;
const containerHeight = this.$refs['scroll-box'].clientHeight;
this.$refs.content.style.transform = `translateY(0px)`;
if (contentHeight > containerHeight) {
// 只有当内容高度超出容器高度时才执行滚动
let scrollPosition = -70;
this.scrollInterval = setInterval(() => {
scrollPosition++;
this.$refs.content.style.transform = `translateY(-${scrollPosition}px)`;
if (scrollPosition >= contentHeight - containerHeight + 20) {
// 当滚动到文本末尾时,返回开头重新开始滚动
scrollPosition = -70;
this.$refs.content.style.transform = `translateY(0)`;
}
}, 50); // 滚动速度,可根据需要调整
}
样式
.scroll-box {
max-height: 25rem;
overflow: hidden;
}
.content {
border-radius: 0.5rem;
// background-color: rgba(1, 100, 1);
font-size: 1.5rem;
color: #FFF;
transition: transform 0.5s ease;
/* 使用过渡效果使滚动更平滑 */
}