以下是实现这个功能的 JavaScript 代码:

// 获取祖先元素和孙子元素
var ancestor = document.getElementById('ancestor');
var grandson = document.getElementById('grandson');

// 获取祖先元素的宽高和滚动条宽度
var ancestorWidth = ancestor.clientWidth;
var ancestorHeight = ancestor.clientHeight;
var scrollbarWidth = ancestor.offsetWidth - ancestorWidth;

// 获取孙子元素的宽高
var grandsonWidth = grandson.offsetWidth;
var grandsonHeight = grandson.offsetHeight;

// 计算滚动条需要滚动的距离
var scrollLeft = grandson.offsetLeft + grandsonWidth / 2 - ancestorWidth / 2;
var scrollTop = grandson.offsetTop + grandsonHeight / 2 - ancestorHeight / 2;

// 滚动祖先元素到孙子元素中心位置
ancestor.scrollLeft = scrollLeft + scrollbarWidth / 2;
ancestor.scrollTop = scrollTop + scrollbarWidth / 2;

需要注意的是,上面的代码假设父元素和孙子元素的位置都是相对于文档的左上角。如果它们的位置是相对于祖先元素的左上角,需要在计算滚动距离时加上父元素的左上角坐标。另外,如果祖先元素有padding、border或margin等样式属性,也需要在计算滚动距离时考虑进去。

JavaScript 实现祖先元素滚动到孙子元素中心位置

原文地址: https://www.cveoy.top/t/topic/ot2x 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录