<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>横向滚动条,选择隐藏滚动条</title>
<style>
ul {
list-style-type: none;
display: flex;
border: 1px solid red;
width: 200px;
padding: 0px;
margin: 5%;
user-select: none;
overflow-x: auto; /* 添加横向滚动 */
white-space: nowrap; /* 防止标签换行 */
/* 禁止文字复制 */
}
/* 隐藏Webkit浏览器的滚动条 */
/* ul::-webkit-scrollbar {
display: none;
} */
li {
border: 1px solid black;
padding: 10px;
margin: 10px;
}
</style>
</head>
<body>
<ul id="tabsContainer">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<script>
var tabsContainer = document.getElementById('tabsContainer');
var isMouseDown = false;
var startX = 0;
var scrollLeft = 0;
tabsContainer.addEventListener('mousedown', function (e) {
isMouseDown = true;
startX = e.pageX - tabsContainer.offsetLeft;
scrollLeft = tabsContainer.scrollLeft;
});
tabsContainer.addEventListener('mouseleave', function () {
isMouseDown = false;
});
tabsContainer.addEventListener('mouseup', function () {
isMouseDown = false;
});
tabsContainer.addEventListener('mousemove', function (e) {
if (!isMouseDown) return;
e.preventDefault();
var x = e.pageX - tabsContainer.offsetLeft;
var walk = (x - startX) * 1; // 调整滚动速度
tabsContainer.scrollLeft = scrollLeft - walk;
});
</script>
</body>
</html>
/* 隐藏Webkit浏览器的滚动条 */
ul::-webkit-scrollbar {
display: none;
}
以上转载前端:横向滚动条,拖动进行左右滚动(含隐藏滚动条)_前端横向滚动-CSDN博客
实战运用导航菜单:
<div className='fenleiList' ref={containerRef} style={{ display: 'flex', maxWidth: '50vw', overflowX: 'hidden', userSelect: 'none' }}
id="tabsContainer"
onMouseDown={handleMouseDown}
onMouseLeave={handleMouseLeave}
onMouseUp={handleMouseUp}
onMouseMove={handleMouseMove}
>
{labelList &&
labelList.map(v => (
<span
key={v.id}
className={categoryActive === v.id ? css(style.tag, style.active) : style.tag}
// style={labelListStyle}
style={{ margin: '0px', minWidth: '180px',maxWidth:'200px', height: '55px', lineHeight: '55px', textAlign: 'center', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', position: 'relative', cursor: 'grab', userSelect: 'none',padding:'0 20px' }}
key={v.id}
onClick={() => {
handleTagClick(v.id);
}}
>
const [isMouseDown, setIsMouseDown] = useState(false);
const [startX, setStartX] = useState(0);
const [scrollLeft, setScrollLeft] = useState(0);
const handleMouseDown = (e) => {
setIsMouseDown(true);
setStartX(e.pageX - e.currentTarget.offsetLeft);
setScrollLeft(e.currentTarget.scrollLeft);
};
const handleMouseLeave = () => {
setIsMouseDown(false);
};
const handleMouseUp = () => {
setIsMouseDown(false);
};
const handleMouseMove = (e) => {
if (!isMouseDown) return;
e.preventDefault();
const x = e.pageX - e.currentTarget.offsetLeft;
const walk = (x - startX) * 1; // 调整滚动速度
e.currentTarget.scrollLeft = scrollLeft - walk;
};
Video_20231220103011