只有当用户向下滚动时,如何使用jQuery将div修复到窗口顶部?

时间:2017-08-23 18:27:32

标签: jquery html css sharepoint sharepoint-2010

我希望当用户向下滚动时,my-sticky-element会被窗口顶部向下推,但只有当用户向下滚动时窗口顶部才会点击my-sticky-element。下面的代码似乎没有按下my-sticky-element(当我在屏幕上向下滚动几百个像素时,窗口的顶部会与元素发生碰撞)。我正在尝试在SharePoint 2010 Web部件中执行此操作。

//store the element
var $cache = $('.my-sticky-element');

//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('margin-top').replace(/auto/, 0));
$(window).scroll(function(event) {
  // what the y position of the scroll is
  var y = $(this).scrollTop();
  // whether that's below the form
  if (y >= vTop) {
    // if so, ad the fixed class
    $cache.addClass('stuck');
  } else {
    // otherwise remove it
    $cache.removeClass('stuck');
  }
});
.my-sticky-element.stuck {
  position: fixed;
  top: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .3);
}

.my-sticky-element {
  background-color: grey;
  color: white;
  font-family: sans-serif;
  padding: 5px 20px;
  width: 200px;
}

.container {
  /*container for centering element*/
  margin: 100px auto;
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="my-sticky-element">I want this item to be pushed down whenever the top of the window hits it. It should be stuck to the top of the window until the user scrolls back up and makes room for it to be visible.
  </div>
</div>

<div style="height:1000px; width: 200px; background-color: yellow;"></div>

0 个答案:

没有答案