这个问题可以通过以下步骤来解决:

  1. 使用CSS将祖先元素设置为固定宽高并启用滚动条属性,使其能够滚动。
  2. 将子元素放置在祖先元素内并设置为超出父元素的宽高,以触发滚动条。
  3. 将孙子元素放置在父元素的中心位置,这可以通过设置父元素为相对定位,然后在其中使用绝对定位来实现。
  4. 使用JavaScript计算出祖先元素滚动条需要滚动的距离,以便将孙子元素滚动到祖先元素的中心位置。

以下是一个示例代码,展示了如何实现上述步骤:

HTML:

<div class="ancestor">
  <div class="parent">
    <div class="child">
      <div class="grandchild"></div>
    </div>
  </div>
</div>

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;

在上面的代码中,我们首先获取了祖先元素和孙子元素的引用,并计算了它们的中心位置。然后,我们计算出需要滚动的距离,并将其应用于祖先元素的滚动条位置。这将使祖先元素滚动到孙子元素的中心位置

祖先元素设置固定宽高设置滚动条属性子元素超出父元素的宽高祖先元素出现滚动条孙子元素在父元素的中心位置父元素和孙子元素的位置都是相对于文档的中心js算出 祖先元素滚动条水平垂直滚动到孙子元素的中心位置

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

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