2015-12-02 46 views
0

Here is the link到頁面我試圖根據需要進行工作。向下滾動綠色塊。標籤塊的左側將粘到屏幕的頂部。所以問題是當左邊到達父元素的末尾時如何去除「sticked」類?如何刪除類,如果相對元素的高度大於窗口滾動?

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

你需要計算包裝的底部位置,並檢查標籤的底部延伸超過這一點 - 如果是這樣,改變定位absolutebottom:0px;,所以它被連接到包裝的底部。

現在它是position: absolute,您需要添加一個檢查以查看屏幕是否已經通過標籤的頂部,如果是,請切換回fixed

總而言之,要進行四項比較和三項可能的結果。此代碼是相當有據可查的解釋:

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

相關CSS

.forlabels-section { 
    position: relative; 
} 
.sticked{ 
    position: fixed; 
    top: 0px; 
    bottom: inherit; 
} 
.sticked2{ 
    bottom:0px; 
    position: absolute; 
    top: inherit; 
} 

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

+0

外觀極好的解決方案。將試圖理解它,並將其附加到我的目標!非常感謝! – NeedHate

相關問題