祖先元素滚动条控制孙子元素居中显示 | 前端JS实现
.ancestor {
width: 200px;
height: 200px;
overflow: auto;
}
.parent {
width: 300px;
height: 300px;
}
.child {
width: 100px;
height: 100px;
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: red;
}
var ancestor = document.querySelector('.ancestor');
var parent = document.querySelector('.parent');
var child = document.querySelector('.child');
// 获取祖先元素的宽度和高度,以及滚动条的宽度和高度
var ancestorWidth = ancestor.clientWidth;
var ancestorHeight = ancestor.clientHeight;
var scrollWidth = ancestor.offsetWidth - ancestorWidth;
var scrollHeight = ancestor.offsetHeight - ancestorHeight;
// 获取孙子元素的宽度和高度
var childWidth = child.offsetWidth;
var childHeight = child.offsetHeight;
// 计算出祖先元素的可滚动区域的宽度和高度
var scrollableWidth = ancestorWidth - scrollWidth;
var scrollableHeight = ancestorHeight - scrollHeight;
// 计算出孙子元素在可滚动区域中心的位置
var centerX = scrollableWidth / 2 - childWidth / 2;
var centerY = scrollableHeight / 2 - childHeight / 2;
// 计算出滚动条需要滚动的距离
var scrollTop = ancestor.scrollTop + centerY - ancestorHeight / 2;
// 将滚动条滚动到计算出的距离
ancestor.scrollTop = scrollTop;
原文地址: https://www.cveoy.top/t/topic/otZS 著作权归作者所有。请勿转载和采集!