固定/粘性div内容在贴在顶部后向左移动

时间:2016-02-25 21:41:22

标签: javascript html css sticky

我想在它下方滚动时将某个div粘贴到顶部。经过一番研究,我发现了这个解决方一切正常,除了在滚动它时div的内容向左移动一点

的javascript

    function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top) {
        $('#sticky').addClass('stick');
    } else {
        $('#sticky').removeClass('stick');
    }
}

$(function () {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

CSS

    #sticky {
    padding: 0.5ex;
    font-size: 2em;
    border-radius: 0.5ex;
}
#sticky.stick {
    position: fixed;
    top: 0;
    z-index: 10000;
    border-radius: 0 0 0.5em 0.5em;
}

HTML

<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
<center>Unternehmen Leistungen Kunden Stärken</center>
<hr /></div>

    function sticky_relocate() {
      var window_top = $(window).scrollTop();
      var div_top = $('#sticky-anchor').offset().top;
      if (window_top > div_top) {
        $('#sticky').addClass('stick');
      } else {
        $('#sticky').removeClass('stick');
      }
    }

    $(function() {
      $(window).scroll(sticky_relocate);
      sticky_relocate();
    });
#sticky {
  padding: 0.5ex;
  font-size: 2em;
  border-radius: 0.5ex;
}
#sticky.stick {
  position: fixed;
  top: 0;
  z-index: 10000;
  border-radius: 0 0 0.5em 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
  <center>Unternehmen Leistungen Kunden Stärken</center>
  <hr />
</div>

1 个答案:

答案 0 :(得分:0)

您必须将div居中以防止这种转变。要将divposition:fixed;居中,您需要将leftright设置为0。

CSS

#sticky.stick {
  position: fixed;
  top: 0;
  left:0;
  right:0;
  z-index: 10000;
}

&#13;
&#13;
function sticky_relocate() {
      var window_top = $(window).scrollTop();
      var div_top = $('#sticky-anchor').offset().top;
      if (window_top > div_top) {
        $('#sticky').addClass('stick');
      } else {
        $('#sticky').removeClass('stick');
      }
    }

    $(function() {
      $(window).scroll(sticky_relocate);
      sticky_relocate();
    });
&#13;
#sticky {
  position:relative;
  padding: 0.5ex;
  font-size: 2em;
  text-align:center;
}
#sticky.stick {
  position: fixed;
  top: 0;
  left:0;
  right:0;
  z-index: 10000;
}

.content {
  height:1000px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
  Unternehmen Leistungen Kunden Stärken
  <hr />
</div>
<div class="content"></div>
&#13;
&#13;
&#13;