JavaScript控制滚动条左右移动
<!DECTYPE html>
<html>
<head>
<meta charset=‘utf-8’>
<title>onwheel-test</title>
</head>
<body>
<div id='out' style='width:500px;height:500px;overflow:auto'>
<div id='inside' style='width:1000px;height:1000px;background-color:gray;overflow:auto'>
</div>
</div>
<script type='application/javascript'>
var outDiv = document.getElementById('out');
outDiv.onwheel = function(event){
event.preventDefault();
var step = 50;
if(event.deltaY < 0){
this.scrollLeft -= step;
} else {
this.scrollLeft += step;
}
}
</script>
</body>
</html>
实例
<div class="layout" id="out">
<div class="b">首页1</div>
<div class="b">首页2</div>
<div class="b">首页3</div>
<div class="b">首页4</div>
<div class="b">首页5</div>
<div class="b">首页6</div>
<div class="b">首页7</div>
<div class="b">首页8</div>
<div class="b">首页</div>
<div class="b">首页</div>
<div class="b">首页</div>
<div class="b">首页</div>
<div class="b">首页</div>
<div class="b">首页</div>
<div class="b">首页</div>
<div class="b">首页</div>
<div class="b">首页</div>
</div>
<div id="addd">
向左
</div>
<div id="addddd">
向右
</div>
<script type='application/javascript'>
var outDiv = document.getElementById('out');
let _scrollLeft = 0
var step = 50;
document.getElementById('addddd').addEventListener('click', () => {
_scrollLeft += step
outDiv.scrollTo(_scrollLeft, 0);
})
document.getElementById('addd').addEventListener('click', () => {
_scrollLeft -= step
outDiv.scrollTo(_scrollLeft, 0);
})
</script>
<style>
.layout {
width: 70%;
height: 50px;
display: flex;
overflow-x: auto;
}
.layout::-webkit-scrollbar {
height: 0px;
}
.b {
width: fit-content;
padding: 0 24px;
height: 50px;
display: flex;
align-items: center;
box-sizing: border-box;
background: red;
color: #ffffff;
white-space: nowrap;
}
</style>