效果:
代码:
单独封装一个addMouseEvent.ts文件
TypeScript
// 添加鼠标移动事件
export const addMouseEvent = (el: string) => {
let container = document.querySelector(el) as HTMLDivElement;
let isMouseDown = false;
let startX = 0;
let scrollLeft = 0;
// 鼠标按下事件
const onMouseDown = (e: MouseEvent) => {
isMouseDown = true;
startX = e.pageX - container.offsetLeft;
scrollLeft = container.scrollLeft;
};
// 鼠标移动事件
const onMouseMove = (e: MouseEvent) => {
if (!isMouseDown) return;
e.preventDefault();
let x = e.pageX - container.offsetLeft;
let walk = (x - startX) * 1; // 调整滚动速度
container.scrollLeft = scrollLeft - walk;
};
// 鼠标抬起事件
const onMouseUp = () => {
isMouseDown = false;
};
// 鼠标离开事件
const onMouseLeave = () => {
isMouseDown = false;
};
container.addEventListener("mousedown", function (e) {
onMouseDown(e);
});
container.addEventListener("mouseleave", function () {
onMouseLeave();
});
container.addEventListener("mouseup", function () {
onMouseUp();
});
container.addEventListener("mousemove", function (e) {
onMouseMove(e);
});
const removeEventListeners = () => {
container.removeEventListener("mousedown", onMouseDown);
container.removeEventListener("mouseleave", onMouseLeave);
container.removeEventListener("mouseup", onMouseUp);
container.removeEventListener("mousemove", onMouseMove);
};
return removeEventListeners;
};
在页面中使用:
.device-list是要执行滑动的dom元素
TypeScript
onMounted(() => {
nextTick(() => {
mouseLeaveEvent.value = addMouseEvent(".device-list");
});
});
onBeforeUnmount(() => {
mouseLeaveEvent.value && mouseLeaveEvent.value();
});
隐藏横向滚动条:
css
::-webkit-scrollbar {
/* 隐藏Webkit浏览器的滚动条 */
display: none;
}