jQuery粘滞按钮

时间:2017-10-24 11:38:04

标签: jquery html css3 twitter-bootstrap-3 scroll

我遇到了jQuery滚动和粘滞按钮的问题。

我有code

$window.scroll(function() {
  var $this = $(this);
  var scrollTop = $this.scrollTop();

  if ($buttonFilter.length > 0) {
    if (scrollTop + windowHeight > buttonFilterFullSize) {
      if ($buttonFilter.hasClass('fixed')) {
        $buttonFilter.removeClass('fixed');
      }
    } else {
      if (!$buttonFilter.hasClass('fixed')) {
        $buttonFilter.addClass('fixed');
      }
    }
  }
});

当隐藏所有折叠时它运行良好,但是当我打开它时,粘性按钮不能很好地工作,并且在我使用滚动时不会跟随。

我可以做些什么来改善我的代码?

1 个答案:

答案 0 :(得分:1)

您应该使用$(document).height();来获取文档高度而不是窗口(浏览器窗口)高度,并且您需要将其放在scroll事件中以在手风琴扩展时刷新值。

至于您需要总计scrollTopwindowHeight的条件。 scrollTop为您提供了Y坐标,windowHeight为您提供了窗口的高度,两者的加起来都是documentHeight

您的代码应如下所示:

 $window.scroll(function() {
     var $this = $(this);
     var scrollTop = $this.scrollTop();
     var documentHeight = $(document).height();
     var windowHeight = $(window).height();

     if ($buttonFilter.length > 0) {
       if ( (scrollTop + windowHeight) === documentHeight) {
         if ($buttonFilter.hasClass('fixed')) {
           //do something....
         }
       } else {
         if (!$buttonFilter.hasClass('fixed')) {
          //do something....
         }
       }

     }