<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
<style>
ul,
li {
margin: 0;
padding: 0;
list-style: none;
}
ul {
display: flex;
column-gap: 10px;
}
li {
flex-shrink: 0;
width: 180px;
height: 100px;
background-color: #eee;
}
</style>
</head>
<body>
<div
id="mybox"
style="
width: 800px;
height: 300px;
background-color: #ccc;
overflow-x: scroll;
"
>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
<script>
var element = document.querySelector("#mybox");
element.addEventListener("wheel", function (event) {
// 阻止默认的滚动行为
event.preventDefault();
// 判断滚轮滚动方向
var direction = event.deltaX > 0 ? "Right" : "Left";
// 根据滚轮滚动方向调整元素的scrollLeft属性
if (direction === "Right") {
element.scrollLeft -= event.deltaY * -1;
} else {
element.scrollLeft += event.deltaY;
}
});
var items = document.querySelectorAll("li");
console.log(items)
items.forEach((item) => {
item.addEventListener("click", scrollToAndCenter);
});
function scrollToAndCenter(event) {
const clickedItem = event.target;
const container = element;
console.log(container.clientWidth)
const containerWidth = container.clientWidth;
const itemWidth = clickedItem.offsetWidth;
const leftBound = clickedItem.offsetLeft;
const centerPosition = leftBound + itemWidth / 2;
// 计算应该滚动的距离,使得元素居中
const scrollDistance = Math.max(0, centerPosition - containerWidth / 2);
// 设置滚动条位置
container.scrollLeft = scrollDistance;
}
</script>
</body>
</html>
网友评论