如果相对元素的高度大于窗口滚动,如何删除类?

时间:2015-12-02 21:38:29

标签: jquery html css

Here is the link第I页我试图根据需要进行工作。向下滚动绿色块。标签块的左侧将粘在屏幕顶部。所以问题是如何删除类"坚持"当这个左侧到达父元素的末尾?

var distance = $('.forlabels').offset().top,
    $window = $(window);

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
       $('.forlabels').addClass('sticked')
    }
  else {
       $('.forlabels').removeClass('sticked')
   } 

  if ($window.scrollTop() >= $('.forlabels').parent().outerHeight())  {
       $('.forlabels').removeClass('sticked')
    }  

});

和html部分:

<div class="fbox">
    <div class="forlabels-section">
    <div class="forlabels">  

      <label for="sect-1" class="tab--element sect-1 tab--checked">+ Интернет-магазин</label>

      <label for="sect-2" class="tab--element sect-2">+ SEO-лендинги</label>

      <label for="sect-3" class="tab--element sect-3">+ Контент-маркетинг</label>

      <label for="sect-4" class="tab--element sect-4">+ Реклама и SEO</label>

      <label for="sect-5" class="tab--element sect-5">+ СуперКонверсия</label>

      <label for="sect-6" class="tab--element sect-6">+ Эксклюзивный дизайн</label>

      <label for="sect-7" class="tab--element sect-7">+ СуперАналитика</label>

</div><!--forlabels-->
 </div><!--forlabels-section-->
  </div><!--fbox-->

1 个答案:

答案 0 :(得分:1)

您需要计算包装器的底部位置,并检查标签的底部是否超出该点 - 如果是,请将定位更改为absolute bottom:0px;,以便&{ #39; s附在包装器的底部。

现在它是position: absolute,您需要添加一项检查以查看屏幕是否再次超过标签的顶部,如果是,请切换回{{1 }}

总而言之,有四个比较和三个可能的结果。这段代码有很好的文档来解释:

fixed

相关的CSS

var $window = $(window);

$window.scroll(function() {
  var labels = $('.forlabels'),
      labelsSec = $('.forlabels-section'),

      bottomOfLabels = labels.outerHeight() + labels.offset().top,
      bottomOfLabelsSec = labelsSec.outerHeight() + labelsSec.offset().top,
      topOfLabels = labels.offset().top,
      topOfLabelsSec = labelsSec.offset().top,

      isAboveTopSec = $window.scrollTop() < topOfLabelsSec,
      isAboveTop = $window.scrollTop() < topOfLabels,
      isBelowTop = $window.scrollTop() >= topOfLabels,
      isBelowBottom = bottomOfLabelsSec <= bottomOfLabels;


  if ( !isAboveTopSec && ((isBelowTop && !isBelowBottom) || isAboveTop)) {
    //  Window is not above the wrapper
    //  Window is past the top of the wrapper, but not past the bottom
    //  Or, the window is above the labels (scrolling up after sticked2)
    $('.forlabels')
      .addClass('sticked')
      .removeClass("sticked2");
  } else if (isBelowBottom) {
    //  Window is past the bottom of the wrapper
    $('.forlabels')
      .addClass('sticked2')
      .removeClass('sticked');
  } else {
    //  Window is above the wrapper
    $('.forlabels')
      .removeClass('sticked sticked2');
  }
});

http://jsfiddle.net/daCrosby/bebq6fb1/1/