JavaScript 滚动祖先元素以将孙子元素置于中心位置
<style>
.ancestor {
width: 200px;
height: 200px;
overflow: auto;
}
.parent {
width: 400px;
height: 400px;
position: relative;
}
.child {
width: 300px;
height: 300px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class='ancestor'>
<div class='parent'>
<div class='child'></div>
</div>
</div>
<script>
const ancestor = document.querySelector('.ancestor');
const parent = document.querySelector('.parent');
const child = document.querySelector('.child');
const ancestorRect = ancestor.getBoundingClientRect();
const parentRect = parent.getBoundingClientRect();
const childRect = child.getBoundingClientRect();
const childCenterX = childRect.left - parentRect.left + childRect.width / 2;
const childCenterY = childRect.top - parentRect.top + childRect.height / 2;
const ancestorScrollX = childCenterX - ancestorRect.width / 2;
const ancestorScrollY = childCenterY - ancestorRect.height / 2;
ancestor.scrollTop = ancestorScrollY;
ancestor.scrollLeft = ancestorScrollX;
</script>
<p>本文将指导您如何通过 JavaScript 将祖先元素滚动,使孙子元素居中显示,即使子元素的尺寸超过父元素。</p>
<p><strong>步骤:</strong></p>
<ol>
<li>
<p><strong>获取元素尺寸和位置信息:</strong> 使用 <code>getBoundingClientRect()</code> 方法获取祖先元素、子元素和孙子元素的宽高和位置信息。</p>
</li>
<li>
<p><strong>计算孙子元素在祖先元素的中心位置坐标:</strong> 通过计算孙子元素在父元素中的偏移量,以及孙子元素自身宽高的一半,得到孙子元素在祖先元素中心位置的坐标。</p>
</li>
<li>
<p><strong>计算祖先元素滚动条需要滚动的距离:</strong> 计算孙子元素中心坐标与祖先元素中心坐标的差值,得到祖先元素滚动条需要滚动的距离,从而使孙子元素处于祖先元素的中心。</p>
</li>
<li>
<p><strong>设置祖先元素滚动条位置:</strong> 使用 <code>scrollTop</code> 和 <code>scrollLeft</code> 属性设置祖先元素的滚动条位置,使孙子元素居中显示。</p>
</li>
</ol>
<p><strong>示例代码:</strong></p>
<p>以上代码片段中,祖先元素具有固定宽高和滚动条属性,子元素尺寸超出父元素,孙子元素位于父元素中心。JavaScript 代码计算祖先元素需要滚动的距离,使孙子元素最终位于祖先元素中心位置。</p>
<p>通过应用这些步骤,您可以轻松实现将孙子元素置于祖先元素中心的效果,即使子元素的尺寸超过父元素。</p>
原文地址: https://www.cveoy.top/t/topic/otZ3 著作权归作者所有。请勿转载和采集!