效果圖
代碼
import { ref, onBeforeUnmount, onUnmounted } from "vue";
//定時器初始化
let timer = ref(null);
//ref綁定初始化
let roll = ref(null);
//等同于vue2中的beforeDestroy
onBeforeUnmount(() => {//清除定時器clearTimeout(timer.value);
});
//等同于vue2中的destroyed
onUnmounted(() => {//清除定時器clearTimeout(timer.value);
});
/*** @Description: 鼠標移動事件* @Author: admin*/
function testMove() {clearTimeout(timer.value);
}
/*** @Description: 鼠標離開事件* @Author: admin*/
function testMend() {start();
}
//開啟定時器方法
function start() {//清除定時器clearTimeout(timer.value);//定時器觸發周期let speed = ref(25);timer.value = setInterval(MarqueeTest, speed.value);
}
function MarqueeTest() {let test1 = roll.value;//判斷組件是否渲染完成if (test1.offsetHeight == 0) {test1 = roll.value;} else {//如果列表數量過少不進行滾動if (test1.childNodes.length < 6) {clearTimeout(timer.value);return;}//組件進行滾動test1.scrollTop += 1;//判斷滾動條是否滾動到底部if (test1.scrollTop == test1.scrollHeight - test1.clientHeight) {//獲取組件第一個節點let a = test1.childNodes[0];//刪除節點test1.removeChild(a);//將該節點拼接到組件最后test1.append(a);}}
}
let tableData = ref([]);
// init 方法是我暴露的方法,父組件通過調用這個方法傳遞列表的數據
const init = val => {tableData.value = val;//注//示例中 listData 寫的靜態數據 可以直接調用start()//如果是接口獲取 listData 列表時 需在 nextTick 中調用 start();否則,//進入頁面不會滾動 必須鼠標移入移出才會滾動//用nextTick 的原因是 需要等dom元素加載完畢后 再執行方法// nextTick(() => {start();// });
};defineExpose({init
});
樣式
首先,你開始循環的盒子的外部的盒子要設置高度和overflow,overflow: scroll,是鼠標移入,可以滑動,overflow: hidden,是鼠標移入沒法滾動,
.scrollClass {width: 100%;height: 100%;overflow: scroll;
}
.scrollClass::-webkit-scrollbar {display: none;
}