Javascript 如何在滚动时修复div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8644248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:53:18  来源:igfitidea点击:

How to fix div on scroll

javascriptjquery

提问by Aaron

If you scroll down the page in the following URL, the 'share' div will lock onto the browser:

如果您在以下 URL 中向下滚动页面,“共享”div 将锁定到浏览器:

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

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

I'm assuming they are applying a position: fixed;attribute. How can this be achieved with jQuery?

我假设他们正在应用一个position: fixed;属性。这如何用 jQuery 实现?

回答by Emre Erkan

You can find an example below. Basically you attach a function to window's scrollevent and trace scrollTopproperty and if it's higher than desired threshold you apply position: fixedand some other css properties.

您可以在下面找到一个示例。基本上,您将函数附加到windowscrollevent 和 tracescrollTop属性,如果它高于所需的阈值,则应用position: fixed和其他一些 css 属性。

jQuery(function($) {
  $(window).scroll(function fix_element() {
    $('#target').css(
      $(window).scrollTop() > 100
        ? { 'position': 'fixed', 'top': '10px' }
        : { 'position': 'relative', 'top': 'auto' }
    );
    return fix_element;
  }());
});
body {
  height: 2000px;
  padding-top: 100px;
}
code {
  padding: 5px;
  background: #efefef;
}
#target {
  color: #c00;
  font: 15px arial;
  padding: 10px;
  margin: 10px;
  border: 1px solid #c00;
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="target">This <code>div</code> is going to be fixed</div>

回答by Julian

On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.

在 jQuery for Designers 上有一篇写得很好的文章,这是发挥魔力的 jQuery 片段。只需将#comment 替换为要浮动的 div 的选择器。

Note:To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/

注意:要查看整篇文章,请访问: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');
    }
  });
});

回答by Facundo Colombier

I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:

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

fiddlehttp://jsfiddle.net/wq2Ej/

小提琴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');
    }
  });

css:

css:

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

回答by Deept Raghav

(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);

and then make any div as floating fixed by calling

然后通过调用将任何 div 设置为浮动固定

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

source: https://github.com/cheald/floatingFixed

来源:https: //github.com/cheald/floatingFixed