简体   繁体   English

加载网页时滚动到 div 的中心

[英]Scrolling to the center of a div when loading the web page

I would like to find out how to achieve centered alignment when loading a page.我想了解如何在加载页面时实现居中对齐。 I have a div which is 4000x2000 pixels and a text which is centered within this div.我有一个 4000x2000 像素的 div 和一个在这个 div 中居中的文本。 Now when reloading I want to scroll to the X so that the X is in the middle.现在重新加载时,我想滚动到 X 以使 X 位于中间。 I have already found something on the internet, unfortunately it does not work for me.我已经在互联网上找到了一些东西,不幸的是它对我不起作用。 What am I doing wrong?我究竟做错了什么?

 let testDiv = document.getElementById("containerTest"); document.addEventListener("DOMContentLoaded", function() { testDiv.scrollTop = testDiv.scrollHeight/2; testDiv.scrollLeft = testDiv.scrollWidth/2; })
 #containerTest{ width: 4000px; height: 2000px; background-color: orange; } .inner-div{ left: 50%; top: 50%; transform: translate(-50%, -50%); font-size: 50px; position: relative; justify-content: center; text-align: center; color: red; }
 <div id="containerTest"> <div class="inner-div">X</div> </div>

This is how it should look after loading:这是加载后的样子: 在此处输入图像描述

@Buggies made a good point about browsers auto scroll after refresh @Buggies 对刷新后浏览器自动滚动提出了一个很好的观点

If you want a more robust solution to scroll to the center, try using scrollIntoView which works even if there's content above/to the left of the container如果您想要一个更强大的解决方案来滚动到中心,请尝试使用scrollIntoView ,即使容器上方/左侧有内容也可以使用

      window.addEventListener("load", function () {
        let testDiv = document.getElementById("containerTest");
        testDiv.scrollIntoView({
          behavior: "auto",
          block: "center",
          inline: "center",
        });
      });

The first problem is auto scroll from browser, info and solution you can find here: Disable brower's auto scroll after a page refresh?第一个问题是从浏览器自动滚动,您可以在此处找到信息和解决方案: Disable brower's auto scroll after a page refresh?

The second problem is that you are scrolling with containerTest but it is not scrollable.第二个问题是您正在使用containerTest滚动,但它不可滚动。 You want to scroll with body/window你想用 body/window 滚动

example:例子:

window.addEventListener('load', function () {
    let testDiv = document.querySelector('#containerTest')
    window.scroll(testDiv.scrollWidth / 2, testDiv.scrollHeight / 2)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM