Подтвердить что ты не робот

Исправить div при прокрутке браузера

Если вы прокрутите страницу вниз по следующему URL-адресу, разделитель "share" будет заблокирован в браузере:

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

Я предполагаю, что они применяют атрибут position: fixed;. Как это можно достичь с помощью jQuery?

4b9b3361

Ответ 1

Ниже приведен пример. В основном вы присоединяете функцию к свойству window scroll события и трассировки 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();
});
body {
  height: 2000px;
  padding-top: 100px;
}
#getFixed {
  color: #c00;
  font: bold 15px arial;
  padding: 10px;
  margin: 10px;
  border: 1px solid #c00;
  width: 200px;
}
<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>

Ответ 2

В 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 below the form
    if (y >= top) {
      // if so, ad the fixed class
      $obj.addClass('fixed');
    } else {
      // otherwise remove it
      $obj.removeClass('fixed');
    }
  });
});

Ответ 3

Я сделал смесь ответов здесь, взял код @Julian и идеи от других, мне кажется яснее, вот что осталось:

fiddle 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 below the form
    if (y >= vTop) {
      // if so, ad the fixed class
      $cache.addClass('stuck');
    } else {
      // otherwise remove it
      $cache.removeClass('stuck');
    }
  });

CSS

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

Ответ 4

(function($) {
  var triggers = [];
  $.fn.floatingFixed = function(options) {
    options = $.extend({}, $.floatingFixed.defaults, options);
    var r = $(this).each(function() {
      var $this = $(this), pos = $this.position();
      pos.position = $this.css("position");
      $this.data("floatingFixedOrig", pos);
      $this.data("floatingFixedOptions", options);
      triggers.push($this);
    });
    windowScroll();
    return r;
  };

  $.floatingFixed = $.fn.floatingFixed;
  $.floatingFixed.defaults = {
    padding: 0
  };

  var $window = $(window);
  var windowScroll = function() {
    if(triggers.length === 0) { return; }
    var scrollY = $window.scrollTop();
    for(var i = 0; i < triggers.length; i++) {
      var t = triggers[i], opt = t.data("floatingFixedOptions");
      if(!t.data("isFloating")) {
        var off = t.offset();
        t.data("floatingFixedTop", off.top);
        t.data("floatingFixedLeft", off.left);
      }
      var top = top = t.data("floatingFixedTop");
      if(top < scrollY + opt.padding && !t.data("isFloating")) {
        t.css({position: 'fixed', top: opt.padding, left: t.data("floatingFixedLeft"), width: t.width() }).data("isFloating", true);
      } else if(top >= scrollY + opt.padding && t.data("isFloating")) {
        var pos = t.data("floatingFixedOrig");
        t.css(pos).data("isFloating", false);
      }
    }
  };

  $window.scroll(windowScroll).resize(windowScroll);
})(jQuery);

а затем сделайте любой div неподвижным, вызвав

$('#id of the div').floatingFixed();

источник: https://github.com/cheald/floatingFixed