console
const containerEl = document.querySelector('.container');
const containerWidth = containerEl.getBoundingClientRect().width;
const screenWidth = window.innerWidth
Array.from(containerEl.children).forEach((item) => {
item.addEventListener('click', function () {
const activeRect = this.getBoundingClientRect()
console.log(activeRect)
adjustScroll(activeRect)
})
})
function adjustScroll(activeRect) {
const size =
containerEl.scrollLeft + activeRect.left - (screenWidth - containerWidth)/2 + activeRect.width / 2;
const translate = size - containerWidth / 2;
containerEl.scrollTo({ left: translate, behavior: 'smooth' });
}
<ol class="container flex overflow-x-scroll">
<li>超级选项1</li>
<li>超级选项2</li>
<li>超级选项3</li>
<li>超级选项4</li>
<li>超级选项5</li>
<li>超级选项6</li>
</ol>
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
}
.container {
background-color: green;
width: 80%;
display: flex;
padding: 0 30px;
overflow-x: scroll;
text-align: center;
}
li {
list-style: none;
flex: auto;
white-space: nowrap;
margin: 0 10px;
padding: 15px;
background-color: white;
cursor: pointer;
}