在Vue中实现垂直滑动css 鼠标按下样式,需要使用一些CSS和JavaScript方法来控制滑动操作
在模板中添加一个包含内容的div元素css 鼠标按下样式,并为其添加ref属性,以便在JavaScript中可以引用它。
<div class="container" ref="container">
</div>
使用 CSS 垂直对齐该 div 元素的子元素,并确保它们不会包裹在父元素内。
.container {
display: flex; /* 将子元素横向排列 */
white-space: nowrap; /* 避免子元素在父元素内换行 */
overflow-x: auto; /* 显示横向滚动条 */
}
编写 JavaScript 代码,以便在用户拖动 div 元素时滚动该元素的内容。
export default {
mounted() {
const container = this.$refs.container; // 获取容器元素
let isDown = false, // 是否按下鼠标
startX, // 鼠标起始位置
scrollLeft; // 滚动条位置
container.addEventListener('mousedown', (e) => {
isDown = true;
startX = e.pageX - container.offsetLeft;
scrollLeft = container.scrollLeft;
});
container.addEventListener('mouseup', () => {
isDown = false;
});
container.addEventListener('mousemove', (e) => {
if (!isDown) return;
e.preventDefault();
const x = e.pageX - container.offsetLeft;
const walk = (x - startX) * 2;
container.scrollLeft = scrollLeft - walk;
});
}
};
总结web端实现滑动,就是对鼠标按下、鼠标松开、鼠标移动事件进行监听
对了最后别忘了隐藏滚动条
::-webkit-scrollbar {
width: 0 !important;
}
::-webkit-scrollbar {
width: 0 !important;
height: 0;
}