将<div>元素设置为固定位置

时间:2018-01-23 10:18:16

标签: javascript jquery html css

我有一个元素<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并在那里得到修复。

2 个答案:

答案 0 :(得分:2)

这应解决问题:

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

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

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

或使用padding-top

答案 1 :(得分:0)

试用此代码

&#13;
&#13;
$( 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");
     }
});
&#13;
<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>
&#13;
&#13;
&#13;