浏览器滚动到它时修复div

Aar*_*ron 36 javascript jquery

如果您向下滚动以下网址中的页面,'share'div将锁定到浏览器:

http://knowyourmeme.com/memes/pizza-is-a-vegetable

我假设他们正在申请一个position: fixed;属性.如何用jQuery实现这一目标?

Emr*_*kan 117

你可以在下面找到一个例子.基本上你附加功能windowscroll事件和跟踪scrollTop财产,如果它比预期的阈值应用position: fixed和一些其他的CSS属性.

jQuery(function($) {
  function fixDiv() {
    var $cache = $('#getFixed');
    if ($(window).scrollTop() > 100)
      $cache.css({
        'position': 'fixed',
        'top': '10px'
      });
    else
      $cache.css({
        'position': 'relative',
        'top': 'auto'
      });
  }
  $(window).scroll(fixDiv);
  fixDiv();
});
Run Code Online (Sandbox Code Playgroud)
body {
  height: 2000px;
  padding-top: 100px;
}
#getFixed {
  color: #c00;
  font: bold 15px arial;
  padding: 10px;
  margin: 10px;
  border: 1px solid #c00;
  width: 200px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="getFixed">This div is going to be fixed</div>
Run Code Online (Sandbox Code Playgroud)

  • @Emre - 如果我使用 `$(window).scroll(fixDiv).resize(fixDiv);` 而不是 `$(window).scroll(fixDiv); fixDiv();` (2认同)

Jul*_*ian 14

在设计师的jQuery上有一篇关于这个问题的精彩文章,这是一个充满魔力的jQuery片段.只需将#comment替换为要浮动的div的选择器.

注意:要查看整篇文章,请访问:http://jqueryfordesigners.com/fixed-floating-elements/

$(document).ready(function () {
  var $obj = $('#comment');
  var top = $obj.offset().top - parseFloat($obj.css('marginTop').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 >= top) {
      // if so, ad the fixed class
      $obj.addClass('fixed');
    } else {
      // otherwise remove it
      $obj.removeClass('fixed');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)


Fac*_*ier 10

我在这里混合了答案,拿了@Julian的代码和其他人的想法,对我来说更清楚,这就是剩下的:

小提琴 http://jsfiddle.net/wq2Ej/

jQuery的

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

//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').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');
    }
  });
Run Code Online (Sandbox Code Playgroud)

CSS:

.my-sticky-element.stuck {
    position:fixed;
    top:0;
    box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}
Run Code Online (Sandbox Code Playgroud)