效果
代码
<!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;
}