[英]Center a one page horizontally scrolling site in browser (not centering a div)
當瀏覽器打開我的頁面時,瀏覽器應該已經位於整個頁面的中心。
含義:我有一個水平的單頁,而不是從左邊開始向右(例如這個 ),將從中間開始,並能夠滾動到右側和左側的內容。
這是一個視覺:
如果可能的話,我想避免通過JavaScript或jQuery進行dom-ready滾動(我正在使用它進行導航輔助和東西),並且只使用純html5 / css或者至少將屏幕重點放在預先准備好的屏幕上的JavaScript / jQuery的。
我的兩個想法:
a)將容器向左移動,例如使用margin-left:-x
,但通常會將其切斷。
b)從一開始就將屏幕向右移動。
唉,我自己太不自然了。
ps這里我的jsfiddle一致性: http : //jsfiddle.net/alexdot/2Dse3/
解
如果要隱藏數據,請添加visibility:hidden;
具有應該在開始時隱藏的內容的元素。 執行我的頁面滾動代碼,最后更改visibility:hidden;
visibility:visible
。
會發生什么事?
visibility:hidden
window.scrollTo(..., ...)
visibility=visible
小提琴: http : //jsfiddle.net/2Dse3/5/
滾動代碼
使用純CSS / HTML無法實現將頁面滾動到中心。 這只能通過使用JavaScript來完成。 出於這個簡單的目的,我寧願使用本機JavaScript而不是包含JQuery插件(不必要的服務器負載)。
JavaScript代碼:
window.scrollTo(
(document.body.offsetWidth -document.documentElement.offsetWidth )/2,
(document.body.offsetHeight-document.documentElement.offsetHeight)/2
);
/*
* window.scrollTo(x,y) is an efficient cross-broser function,
* which scrolls the document to position X, Y
* document.body.offsetWidth contains the value of the body's width
* document.documentElement contains the value of the document's width
*
* Logic: If you want to center the page, you have to substract
* the body's width from the document's width, then divide it
* by 2.
*/
你必須調整CSS(見小提琴 ):
body {width: 500%}
#viewContainer {width: 100%}
最后一點。 當用戶禁用JavaScript時,您期望什么? 他們是否可以看到頁面內容? 如果是,請添加以下內容:
<noscript>
<style>
.page{
visibility: visible;
}
</style>
</noscript>
否則,添加<noscript>JavaScript is required to read this page</noscript>
。
一個簡單的jQuery解決方案
$(function () {
scrollTo(($(document).width() - $(window).width()) / 2, 0);
});
DOM-ready有什么問題?
$(function() {
$('body').scrollLeft($('#viewContainer').width() * 2/5);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.