簡體   English   中英

使用 HTML/CSS 的浮動菜單欄?

[英]Floating menu bar using HTML/CSS?

想知道是否有人知道一種創建浮動菜單欄的方法,該菜單欄會固定在頁面上的某個點上,直到瀏覽器窗口在頁面下方足夠遠並將其松開,然后菜單欄開始隨之滾動。 我想要的效果和這個http://www.jtricks.com/javascript/navigation/floating.html javascript 菜單完全一樣。 但是,我真的很想用 CSS 來做到這一點。 我知道我可以使 div 絕對定位,它會在頁面上向下移動,我嘗試使一個 DIV 相對定位(父 div),然后在其中設置另一個絕對定位的 div,但我無法讓它工作。 有誰知道如何使用 CSS 進行這項工作,還是需要使用 JS?

提前致謝。

喬恩。

我相信使用 javascript 是獲得您描述的效果的唯一解決方案。 這是一個以絕對位置開始並在用戶滾動時固定的橫幅的快速演示

<div style="height:1000px;width:500px;">

    <div id="floatbar" style="background:gray;
                                width:200px;
                                height:40px;
                                position:absolute;
                                left:0;top:200px;">
    </div>
</div>

$(window).scroll(function(){
    if ($(window).scrollTop() >= 200)
    {
        $("#floatbar").css({position:'fixed',left:'0',top:'0'});
    }
    else
    {
        $("#floatbar").css({position:'absolute',left:'0',top:'200px'});
    }
});

好吧,如果你不需要動畫,而不僅僅是使用
position: fixed;
在css中。

如果你想要動畫,你需要使用 javascript。 例如在 jquery 中:

$(window).scroll(function(){
   $('#menu').css({
       right: 0,
       top: 0
   })
})

好吧,你不能用相對內的絕對定位 div 來做到這一點。 固定位置基本上是一個絕對定位的div,相對於窗口定位。 我會說你在這里肯定需要javascript。

使用固定的側邊欄和浮動內容部分,這應該很容易。 嘗試這樣的事情......

#container {
    width: 960px;
    margin: 0 auto;
    overflow: hidden;
    position: relative;
}

#sidenav {
    width: 300px;
    position: fixed; /*--Fix the sidenav to stay in one spot--*/
    float: left; /*--Keeps sidenav into place when Fixed positioning fails--*/
}

#content {
    float: right; /*--Keeps content to the right side--*/
    width: 620px;
    padding: 0 20px 20px;
}

我相信它需要是JS。 我可以想象使用 jQuery 可能會相當簡單,而且我真的想不出任何方法來僅使用 CSS 來實現這一點。 我會試着考慮一下,但我懷疑我會找到解決方案。

這是舊帖子,但自那時起 CSS 發生了很大變化,我們可以使用純 CSS 來制作浮動菜單。 請參閱下面的示例代碼。 歸功於https://www.quackit.com/css/codes/css_floating_menu.cfm

 main { margin-bottom: 200%; } .floating-menu { font-family: sans-serif; background: yellowgreen; padding: 5px;; width: 130px; z-index: 100; position: fixed; right: 0px;/* You can change float left/right */ } .floating-menu a, .floating-menu h3 { font-size: 0.9em; display: block; margin: 0 0.5em; color: white; }
 <!DOCTYPE html> <title>Example</title> <main> <p>Scroll down and watch the menu remain fixed in the same position, as though it was floating.</p> <nav class="floating-menu"> <h3>Floating Menu</h3> <a href="/css/">CSS</a> <a href="/html/">HTML</a> <a href="/database/">Database</a> </nav> </main>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM