将div定位到滚动到父div的固定位置

时间:2019-11-15 12:34:35

标签: javascript jquery html

我有一个div scroll-content,其中包含另一个div fixme,只有在scroll-content div位于屏幕顶部时,我才想对其进行修复。如果用户滚动经过scroll-content格,则fixme应该消失。我正在使用下面的代码,但它似乎不起作用:

var fixmeTop = $('.fixme').offset().top;
$(window).scroll(function() {
  var currentScroll = $(window).scrollTop();
  if (currentScroll >= fixmeTop) {
  
    $('.fixme').css({
      position: 'fixed',
      top: '50%',
      left: '50%',
      display: 'block'
    });
  } else {
  $('.fixme').css({
 
      display: 'none'
    });
  } 
  
});
body {
  height: 3000px;
}

.content {
  height: 500px;
  background: white;
}

.scroll-content {
  background: black;
  height: 1000px;
}

.fixme {
  background: green;
  color: white;
  text-align: center;
  width: 100px;
  height: 100px;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div class="content"></div>

<div class="scroll-content">
<div class="fixme">Scroll here</div>
</div>

1 个答案:

答案 0 :(得分:0)

这是一个使用位置粘性将.fixme元素保留在.scroll-content元素内的示例。由于jQuery用position覆盖了fixed属性,因此您自己尝试之前可能无法使用。

我希望这是理想的效果。
否则,请告知我们,以便我们帮助您找到另一种解决方案。

body {
  height: 3000px;
}

.content {
  height: 500px;
  background: white;
}

.scroll-content {
  position: relative;
  background: black;
  height: 1000px;
}

.fixme {
  position: sticky;
  top: calc(50% - 50px);
  left: 50%;
  background: green;
  color: white;
  text-align: center;
  width: 100px;
  height: 100px;
  transform: translate(-50%, 0%);
}
<div class="content"></div>
<div class="scroll-content">
  <div class="fixme">Scroll here</div>
</div>