簡體   English   中英

組 <div> 元素到固定位置

[英]Set <div> element to fixed position

我有一個元素<div class="stock-list-head"></div> 此元素包含產品列表的標題(商品編號,商品名稱,價格...)。

因此,我希望在滾動產品時固定該div (實際上,滾動時產品必須在<div>后面)。

我嘗試使用jquery函數捕獲滾動事件:

 $( document ).scroll(function(){
     var scroll = $(window).scrollTop();
     if(scroll>1){
         $(".stock-list-head").css("position", "fixed");
         $(".stock-list-head").css("top", "10px");
         $(".stock-list-head").css("marginTop", "-101px");
         // And some similar styles but without success.
     }
}

一直以來,div下降了50px,並在那里固定。

這應該可以解決問題:

 body { height: 1500px; } * { margin: 0; } h2 { margin: 0 16px; display: inline-block; font-size: 32px; line-height: 56px; } header { overflow: auto; } header, #header-fix { display: block; height: 56px; box-sizing: border-box; background: #5b27ad; color: white; font-weight: 700; font-family: "Roboto", sans-serif; margin: 0; } header.fixed { top: 0; left: 0; position: fixed; z-index: 9999; width: 100%; } div.fixed { height: 0; display: none; } div { width: 300px; height: 200px; margin: 8px; display: inline-block; background: seagreen; } 
 <header class="fixed"> <h2>Logo here</h2> </header> <div id="header-fix" class="fixed"></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> 

另外,您可以使用其他方法(但在某些情況下可能會很差)-添加CSS

body {
    margin-top: <here header height>; /* you can check height with devtools */
}

或使用padding-top

試試這個代碼

 $( document ).scroll(function(){ var scroll = $(window).scrollTop(); if(scroll>1){ $(".stock-list-head").css("position", "fixed"); $(".stock-list-head").css("top", "0px"); // And some similar styles but without success. }else if(scroll == 0){ $(".stock-list-head").css("position", "relative"); $(".stock-list-head").css("top", "0px"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header class="stock-list-head"> <h4>Header</h4> </header> <div>test</div> <div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div><div>test</div> 

暫無
暫無

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

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