我怎样才能确保一个网页打开与滚动条在中间



我试图创建一个水平滚动页面,我希望页面打开与滚动条在中间,以便用户有选项滚动在左边和右边的方向(默认情况下,它打开在左边的滚动条)。我该怎么做呢?

注释后更新如果body的宽度不超过浏览器的视口:
在元素内滚动:

var elem = document.getElementById("container"); //div#container
var elemWidth = elem.scrollWidth;
var elemVisibleWidth = elem.offsetWidth;
elem.scrollLeft = (elemWidth - elemVisibleWidth) / 2;


使用此代码将&水平居中(参见:this answer):

 window.scrollTo(
     (document.body.offsetWidth -window.innerWidth )/2,
     (document.body.offsetHeight-window.innerHeight)/2
 );

只在水平居中,使用:

window.scrollTo((document.body.offsetWidth -window.innerWidth )/2, 0);

onload事件中使用JavaScript函数scrollTo。有关如何获取当前窗口大小的更多信息,请参阅本文。

一种可能性是在加载页面时使用javascripts scrollto(只需将其放在您的onload或domready-event中):

window.onload = function(){
  window.scrollTo(100, 100); // (X,Y)
}

将x/y值设置为您需要的值

另一种方法是# href。如果你没有问题的尾部标签添加到url

 $("#iwillHelp")[0].click();
    body{
    margin: 0;
}
.top{
    width:100vw;
    height: 100vh;
    background-color: red;
}
.mid{
    width:100vw;
    height: 100vh;
    background-color: green;
}
.bottom{
    width:100vw;
    height: 100vh;
    background-color: blue;
}
<body id="mainBody">
    <div class="top">how to land at the middle of webpage</div>
    <a id="iwillHelp" href="#testCenter"></a>
    <div class="mid" id="testCenter">How to land in this green coloured section</div>
    <div class="bottom">Please help me</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

最新更新