祖先元素设置固定宽高设置滚动条属性子元素超出父元素的宽高祖先元素出现滚动条孙子元素在父元素的中心位置js算出 祖先元素滚动条滚动到孙子元素的中心位置
可以使用以下步骤来实现:
-
获取祖先元素和孙子元素的宽高以及位置信息。
-
计算出孙子元素在祖先元素中心位置的坐标。
-
计算出祖先元素滚动条需要滚动的距离,使得孙子元素在祖先元素中心位置。
-
使用scrollTop和scrollLeft属性设置祖先元素的滚动条位置。
以下是一个示例代码:
<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>
在这个示例中,祖先元素是一个具有固定宽高和滚动条属性的元素,子元素超出了父元素的宽高,孙子元素在父元素的中心位置。使用JavaScript计算出祖先元素需要滚动的距离,使得孙子元素在祖先元素中心位置。然后使用scrollTop和scrollLeft属性设置祖先元素的滚动条位置
原文地址: https://www.cveoy.top/t/topic/gcRQ 著作权归作者所有。请勿转载和采集!