<template>
<div class="scroll-wrapper" ref="divDom" :class="noHeader ? 'no-header' : ''" @mouseover="mouseover" @mouseout="mouseout">
<div class="scroll-box" ref="scrollDom">
<div class="page-r-item" v-for="(item,index) in scrollData" :key="index">
<!-- 你要加的内容-->
</div>
</div>
</div>
</template>
<script lang="ts">
import {computed, defineComponent, nextTick, onDeactivated, onMounted, onUnmounted, reactive, ref, toRefs} from "vue";
export default defineComponent({
name: 'MyScroll',
components: {},
props: {
noHeader: {
default: false,
type: Boolean,
},
attenancePStatistics:{
default:()=>[],
type:Array
}
},
emits: [],
setup(props, {emit, attrs, slots}) {
let divDom = ref();
let scrollDom = ref();
let state = reactive({
scrollData:computed(()=>{
if(state.isMulti){
return [...props.attenancePStatistics,...props.attenancePStatistics]
}else{
return props.attenancePStatistics
}
}),
isMulti:false,//如果内容超过了高度就加定时器并数据加双份
timer: <any>0,
step:0,
clearTimer() {
clearInterval(state.timer);
state.timer=0
},
wrapper_height:0,
content_height:0,
initScroller(type) {
state.clearTimer();
state.timer = setInterval(() => {
let wrapper = divDom.value;
let content = <HTMLElement>document.getElementsByClassName('scroll-box')[0]
state.wrapper_height = wrapper.clientHeight
state.content_height = scrollDom.value.clientHeight
if(state.content_height>=state.wrapper_height){
state.isMulti=true
}else{
state.isMulti = false
state.clearTimer();
return
}
state.step-=1
if(state.step<=-(scrollDom.value.clientHeight/2)){
state.step = 0
}
content.style.top = state.step +'px'
}, 30)
},
mouseover() {
state.clearTimer();
},
mouseout() {
state.initScroller('mouseout');
},
});
onMounted(() => {
state.initScroller('init');
setTimeout(()=>{
if(state.content_height===0){
//因为获取不到scroll的高度所以这里加了定时器,也许有更好的方法,欢迎一起探讨
state.initScroller('init');
}
},1000)
window.addEventListener('resize',()=>state.initScroller('init'))
})
onUnmounted(() => {
state.clearTimer();
document.removeEventListener('resize',()=>state.initScroller('init'))
});
onDeactivated(() => {
state.clearTimer();
})
return {
...toRefs(state),
divDom,
scrollDom,
attrs,
slots,
};
}
})
</script>
<style lang="less" scoped>
* {
scroll-behavior: smooth;
transform:translate3d(0,0,0);
}
.scroll-wrapper{
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
scroll-behavior: smooth;
.scroll-box{
position: absolute;
}
}
</style>