1. 首先需要两个包裹的元素
2.外层元素肯定比内层宽度小;
3.然后对外层元素使用overflow-y:hidden;
4.其次不可以让里面的元素换行(假如使用了flex布局的话,那就设置flex-wrap:nowarp);
5.以上在移动端直接水平可以拖动,在PC端还需要加上js;如下;
let el = document.getElementsByClassName(‘header-index‘)[0];
// el.style.cursor = ‘grab‘;
// console.log(el);
el.onmousedown = function() {
el.style.cursor = ‘grabbing‘;
let gapX = event.clientX;
let startX = el.scrollLeft;
document.onmousemove = function(e) {
let x = e.clientX - gapX;
el.scrollLeft = startX - x;
return false;
};
document.onmouseup = function() {
el.style.cursor = ‘grab‘
document.onmousemove = null;
document.onmouseup = null;
};
};
html实现鼠标点击水平拖动元素