I am trying to create a horizontally scrolling page and I want the page to open with scroll bar in the middle so that the user has option to scroll in both left and right directions(by default it opens with scrollbar at left). How can I do that?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Updated after comment If the body's width doesn't exceed the browser's viewport:
Scrolling inside an element:
var elem = document.getElementById("container"); //div#container
var elemWidth = elem.scrollWidth;
var elemVisibleWidth = elem.offsetWidth;
elem.scrollLeft = (elemWidth - elemVisibleWidth) / 2;
Use this code to vertically & horizontally center a page (see also: this answer):
window.scrollTo(
(document.body.offsetWidth -window.innerWidth )/2,
(document.body.offsetHeight-window.innerHeight)/2
);
To only center horizontally, use:
window.scrollTo((document.body.offsetWidth -window.innerWidth )/2, 0);
回答2:
Use the JavaScript function scrollTo
in the onload
event. For more information on how to get the current window size, check out this article.
回答3:
one possibility is to use javascripts scrollto
when loading the page (simply put this in your onload or domready-event):
window.onload = function(){
window.scrollTo(100, 100); // (X,Y)
}
just set the x/y values to the ones you need.