在我们平时的项目需求中可能会遇到这样的需求,就是多个数据,同时只能展示出3个,这时候就该用上我们的滑动了,先设置css样式
先设置父盒子样式
.centerContainer {
width: 90%;
height: 100%;
// background-color: #fff;
padding: 0 20px;
display: flex;
overflow: hidden;
}
下面是子盒子,子盒子的数量一定要大于3个,flex-shrink很关键
.box {
width:33%;
height: 100%;
/* 超出滚动的关键,没有它元素会自动缩小,不会滚动 */
flex-shrink: 0;
margin: 0 30px;
}
下面到js代码部分,因为我们是在vue中使用的所以这些代码需要加到mounted中
const container = this.$refs.centerContainer; // 获取容器元素
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;
});
// 添加鼠标移出事件
container.addEventListener('mouseleave', (e) => {
// console.log('移出了',e);
isDown = false;
});
以上便能够实现盒子内的滑动了,如果想多加上一些功能的话,看下面
先说滚动条后移
currentAdd() {
const container = this.$refs.centerContainer; // 获取容器元素
console.log(container.offsetWidth, 'container');
console.log(container.scrollLeft, 'container');
// 判断滚动条是否到达最右边
if (container.scrollWidth > container.clientWidth) {
if (container.scrollLeft + container.clientWidth >= container.scrollWidth) {
// console.log('滚动条已到达最右边');
this.$message.success('暂无更多数据了')
} else {
console.log('滚动条未到达最右边');
}
} else {
console.log('滚动条无法滚动');
}
add(container.offsetWidth / 3)
function add(num) {
let i = 0;
const step = () => {
if (i < num) {
container.scrollLeft += 8;
i += 8;
if (i < num) {
setTimeout(step, 0);
}
}
};
step();
}
},
下面是往前
currentSub() {
const container = this.$refs.centerContainer; // 获取容器元素
console.log(container.offsetWidth, 'container');
console.log(container.scrollLeft, 'container');
if(container.scrollLeft==0){
this.$message.success('前面暂无更多数据了')
}
subtract(container.offsetWidth / 3)
function subtract(num) {
let i = num;
const step = () => {
if (i > 0) {
container.scrollLeft -= 8;
i -= 8;
if (i > 0) {
setTimeout(step, 0);
}
}
};
step();
}
},
因为一次性改变它的scrollLeft 会给我们一种卡顿的现象,所以在移动的时候我加了一些处理,这样看起来更平滑,更顺畅