窗口滚动事件中的中心div

时间:2018-04-13 09:43:53

标签: javascript jquery

如何使用窗口滚动事件将div居中?我很长一段时间都在寻找这个答案。任何帮助将不胜感激。



$(window).scroll(function() {
  var offSetTop = $("#ifOne").offset().top;
  var positionTop = $("#ifOne").position().top;
  var windowHeight = $(window).height();
  var scrollTop = $(window).scrollTop();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">Some Content</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

一个简单的演示展示了如何使div居中:

&#13;
&#13;
$(window).scroll(function() {
  var offSetTop = $("#div1").offset().top;
  var positionTop = $("#div1").position().top;
  var windowHeight = $(window).height();
  var scrollTop = $(window).scrollTop();
  var top = scrollTop + (windowHeight - $("#div").height())/2
  $('#div1').css('top', top)
});
&#13;
#container{
  position: relative;
  height: 200vh;
  width: 100%;
}

#div1{
  position: relative;
  margin: 0 auto;
  width: 100px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="div1">
    Some Content
  </div>
</div>
&#13;
&#13;
&#13;