点击元素,使该元素滚动到屏幕中间
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/013c90f44f731ad5510c2c9ee74fa065.gif#pic_center)
<!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>scroll-to-view-center</title>
</head>
<style>
* {
padding: 0;
margin: 0;
list-style: none;
}
li {
line-height: 100px;
text-align: center;
background: skyblue;
}
li:nth-child(odd) {
background-color: pink;
}
</style>
<body>
<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>
<script>
function getWindowScrollTop() {
var scroll_top = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scroll_top = document.documentElement.scrollTop;
} else if (document.body) {
scroll_top = document.body.scrollTop;
}
return scroll_top;
}
function scrollToViewCenter(el) {
const { top, height } = el.getBoundingClientRect();
const elCenter = top + height / 2;
const center = window.innerHeight / 2;
window.scrollTo({
top: getWindowScrollTop() - (center - elCenter),
behavior: 'smooth'
});
}
document
.querySelectorAll('li')
.forEach((el) => el.addEventListener('click', (e) => scrollToViewCenter(e.target)));
</script>
</body>
</html>