在关注元素的同时,页面不会在firefox和IE中滚动?

问题描述 投票:1回答:1

我试图使用焦点方法将元素集中在我的页面中。当元素聚焦时,页面会自动滚动到聚焦元素。但在firefox和IE浏览器页面中滚动不正确。所以我的焦点元素在页面底部可见。

步骤:在chrome中运行示例,元素将出现在页面中间。在Firefox中,它将显示在页面底部。

怎么解决?

setTimeout(() => {
  document.getElementById('parent-element').focus();
}, 10);
body {
  touch-action: none;
}

#target {
  height: 2000px;
  background-color: aliceblue;
}

#parent-element {
  max-height: 980px;
  width: 400px;
  left: 150px;
  top: 958px;
  display: inline-flex;
  background-color: #fff;
  box-shadow: 0 12px 40px 5px rgba(0, 0, 0, 0.26);
  max-width: 100%;
  min-width: 240px;
  height: auto;
  position: absolute;
}

.Child-element {
  border-bottom: none;
  padding: 18px;
  border-radius: 1px 1px 0 0;
  line-height: 30px;
  background-color: #fff;
}

.childcontent {
  display: block;
  width: 83%;
  color: rgba(0, 0, 0, 0.87);
}
<div id="target">
  <div id="parent-element" role="dialog" tabindex="-1">
    <div class="Child-element">
      <div class="childcontent">Am developer</div>
    </div>
  </div>
</div>
javascript html
1个回答
-1
投票

我可以提供一个experimental替代解决方案,我试图弄清楚为什么Firefox不以焦点()为中心。

如果你想要的话,scrollIntoView()将为你工作,将div滚动到页面的中心。再次,它的实验,但我在最新的Chrome和Firefox浏览器中测试它,它在那里工作。

您可以使用以下内容:

document.getElementById('parent-element').scrollIntoView({behavior: "instant", block: "center"});

您可以从这两个资源中检查浏览器兼容性。 MDNCan I Use

© www.soinside.com 2019 - 2024. All rights reserved.