一、解决方案
滚动的元素.scrollLeft = (滚动的元素.clientWidth - 外层盒子.clientWidth)/ 2
完整DEMO
<!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>Document</title>
<style>
.f {
width: 300px;
height: 300px;
border: 1px solid red;
overflow-x: scroll;
margin: 0 auto;
}
.s {
width: 1200px;
height: 200px;
background-color: #ff0005;
display: flex;
justify-content: center;
align-items: center;
}
h1 {
color: #fff;
}
/*
// 400 100
// 500 200
// 1000 700
// 1500 1200
// 20000 1700
*/
</style>
</head>
<body>
<div class="f">
<div class="s">
<h1>red</h1>
</div>
</div>
<script>
let f = document.querySelector('.f')
let s = document.querySelector('.s')
window.addEventListener('load',function(){
//滚动条位置居中
f.scrollLeft = (s.clientWidth - f.clientWidth) / 2
})
f.addEventListener('scroll',function(){
console.log(f.scrollLeft);
})
</script>
</body>
</html>
二、原理
通过观察元素滚动事件,滚动条的最大滚动距离为,滚动的元素的宽- 外层盒子的宽。 所以剧中只需将元素滚动距离左侧 最大滚动位置的一半就OK了。