CSS 和 JavaScript 实现滚动到孙子元素中心位置
CSS:
.ancestor { width: 500px; height: 500px; overflow: auto; position: relative; }
.parent { width: 1000px; height: 1000px; position: relative; }
.child { width: 1500px; height: 1500px; }
.grandchild { width: 200px; height: 200px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
JavaScript:
const ancestor = document.querySelector('.ancestor'); const grandchild = document.querySelector('.grandchild');
const ancestorCenterX = ancestor.offsetWidth / 2; const ancestorCenterY = ancestor.offsetHeight / 2;
const grandchildCenterX = grandchild.offsetLeft + grandchild.offsetWidth / 2; const grandchildCenterY = grandchild.offsetTop + grandchild.offsetHeight / 2;
const scrollX = grandchildCenterX - ancestorCenterX; const scrollY = grandchildCenterY - ancestorCenterY;
ancestor.scrollLeft = scrollX; ancestor.scrollTop = scrollY;
在上面的代码中,我们首先获取了祖先元素和孙子元素的引用,并计算了它们的中心位置。然后,我们计算出需要滚动的距离,并将其应用于祖先元素的滚动条位置。这将使祖先元素滚动到孙子元素的中心位置。
原文地址: https://www.cveoy.top/t/topic/ot3q 著作权归作者所有。请勿转载和采集!