2017-08-02 64 views
-1

我想讓我的頁腳「粘」,但高度各不相同,因此無法使用我找到的大多數方法或flexbox。有沒有什麼辦法用JavaScript來檢查div下面有多少空間,所以我可以添加多少空白?如何使有條件的「粘」頁腳?

的HTML如下:

<container> 
    <header></header> 
    <body><sometimes sub content></sub content></body> 
    <footer></footer> 
    </container> 

還試圖把頁腳的容器外,看到了一些解決方案,但他們又都需要一個固定的高度。

+1

這將有助於別人理解你的問題,如果你可以添加一些你的HTML標記,那你到目前爲止的JavaScript代碼。 – Nisarg

+0

這不是div下的空間,因爲它是頁腳的高度,是的?我假設你的問題是你的頁腳正在遮蓋內容,對吧?如果是這樣,如果你的頁腳沒有空白/填充,你可以簡單地做一個'$(「body」)。css(「margin-bottom」,$(「footer」)。height()+「px」' – mhodges

+0

否,在沒有太多內容的頁面上,頁腳位於屏幕中間的內容末尾,我想讓它保持在窗口的底部,但是在其他頁面上更多的內容我想在內容 – nick

回答

1

您可以檢查是否$(document).height() > $(window).height()。這會告訴你內容的高度是否比視口長。如果是這樣,請將頁腳留在原來的位置。如果文檔高度爲< =視口高度,請添加頁腳粘性。如下所示:

要查看粘性和非粘性之間的區別,請運行以下代碼片段以使頁腳位於頁面底部。要查看頁腳粘滯的位置,請在全屏模式下(代碼段輸出的右上角)運行代碼段。您也可以在全屏模式下運行它,然後縮小瀏覽器大小 - 重新計算窗口大小。

$(window).on("load resize", function() { 
 
    // if content height <= viewport height, make footer sticky 
 
    // else leave footer at the bottom of the content. 
 
    $(".footer").toggleClass("sticky", $(document).height() <= $(window).height()); 
 
});
.footer { 
 
    width: 100%; 
 
    background-color: #555588; 
 
    color: white; 
 
} 
 

 
.sticky { 
 
    position: fixed; 
 
    bottom: 0; 
 
    left: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<pre style="font-size: 16px;"> 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
    content 
 
</pre> 
 
<div class="footer">foo foo foo <br/>foo<br/>foo<br/></div>

+0

哇,怪異的!爲什麼它會將我的編輯分成一個新帖子? – mhodges

+0

關於你的mod標誌,很遺憾我們很少能夠幫助你。雖然我們可以合併兩個*問題*(移動a從愚蠢到主人,保留他們的選票),我們不能合併兩個*答案*。我不知道你的編輯如何分成新的職位。他們不應該。如果您確定*您沒有無意中點擊「添加另一個答案」,那麼您應該在[Meta]上發佈錯誤報告。無論如何,關於手頭的問題,唯一可以做的就是刪除舊的,過時的答案。我已經爲你做了。只有10分輸了;沒什麼大不了的。 –

1

您可以將main的最小高度設置爲100vh,並將頁腳完全放置在底部。主要應該有底部填充至少頁腳的高度,box-sizing: border-box主要是100vh高度。

然而,看到粘腳在行動的例子。

body { 
 
    margin: 0; 
 
} 
 

 
main { 
 
    position: relative; 
 
    padding-bottom: 60px; 
 
    min-height: 100vh; 
 
    box-sizing: border-box; 
 
} 
 

 
.hidden { 
 
    background: blue; 
 
    height: 100vh; 
 
} 
 

 
main:not(:hover) > .hidden { 
 
    display: none; 
 
} 
 

 
footer { 
 
    position: absolute; 
 
    width: 100%; 
 
    height: 50px; 
 
    bottom: 0; 
 
    background: red; 
 
}
<main> 
 
    <article>Short Article</article> 
 
    
 
    <article class="hidden"> 
 
    long article 
 
    </article> 
 
    
 
    <footer> 
 
    I'm the footer 
 
    </footer> 
 
</main>