我正在尝试创建水平滚动页面,我想要打开页面,中间有滚动条,以便用户可以选择向左滚动和正确的方向(默认情况下,左侧滚动条打开)。我怎么能这样做?
答案 0 :(得分:1)
评论后更新如果正文的宽度不超过浏览器的视口:
在元素内滚动:
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);
答案 1 :(得分:0)
在onload
事件中使用JavaScript函数scrollTo
。有关如何获取当前窗口大小的更多信息,请查看this article。
答案 2 :(得分:0)
一种可能性是在加载页面时使用javascripts scrollto
(只需将其放在onload或domready - 事件中):
window.onload = function(){
window.scrollTo(100, 100); // (X,Y)
}
只需将x / y值设置为您需要的值即可。
答案 3 :(得分:0)
另一种方式是#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>