2016-02-19 36 views
5

我想通過使用jQuery在用戶距頂端不同距離時刪除/添加類。使用jQuery在頁面上的不同高度添加和刪除類

我已經成功地完成了它,它工作正常,但我認爲我做錯了,我希望你的幫助來優化代碼。

html很簡單,基本上這些部分(包括標題)具有100%的寬度。和不同的顏色。我想在第一部分(爲了美學目的)改變標題的顏色。 而且我還希望它在頁面滾動超過1個像素時有陰影。

我正在通過添加/刪除類來做到這一點。

當我使用一個大的if語句時,它不能很好地工作,因爲每當任何條件匹配時,js就停止檢查其他匹配項,所以它不適用所有需要的類。

接下來的代碼有效,但正如我所說的,我認爲這不是最佳/不好的寫法。 下面是HTML標記:

<header class="dark no-shadow"> 
    Header 
</header> 
<section class="blue"> 
    Please Scroll Down to see the header changes... 
</section> 
<section> 
    The header color Should change when you pass through me. 
</section> 

這裏是jQuery代碼:(!像我)

var header = $('header'), 
     blueSection = $('section.blue'), 
    // Calculate when to change the color. 
     offset = blueSection.offset().top + blueSection.height() - header.height(); 

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

    // Remove Class "dark" after scrolling over the dark section 
    if (scroll >= offset) { 
    header.removeClass('dark'); 
    } else { 
    header.addClass('dark'); 
    } 

    // Remove Class "no-shadows" whenever not on the top of the page. 
    if (scroll >= 1) { 
    header.removeClass('no-shadow'); 
    } else { 
    header.addClass('no-shadow'); 
    } 

}); 

而對於那些你們誰喜歡用的jsfiddle: https://jsfiddle.net/shock/wztdt077/6/

感謝前面的傢伙!

+0

在這裏查看如何在您滾動某處後執行操作 - http://stackoverflow.com/questions/25660289/show-hide-div-when-passed-the-other-div/25661103#25661103 - 您可以通過div的位置或像素 – Tasos

+0

演示使用以上的代碼 - https://jsfiddle.net/tgaoyx4b/ – Tasos

+2

這可能應該去http://codereview.stackexchange.com/ – xpy

回答

1

Here是我想出來的:

var header = $('header'), 
    blueSection = $('section.blue'), 
    // Calculate when to change the color. 
    offset = blueSection.offset().top + blueSection.height() - header.height(); 

var add = function(obj, cls) {obj.addClass(cls);} 
var remove = function(obj, cls) {obj.removeClass(cls);} 

var stylePoints = [offset, 1,   100, 200]; 
var styleTo =  ['dark', 'no-shadow', 'blue', 'tall']; 
var styleType = [add, add,   remove, remove]; 

$(window).scroll(function() { 
    var scroll = $(window).scrollTop(); 
    for (i = 0; i < stylePoints.length; i++) { 
    var func = styleType[i]; 
    if (scroll >= stylePoints[i]) 
     (styleType[i] == add) ? remove(header, styleTo[i]) : add(header, styleTo[i]); 
    else func(header, styleTo[i]); 
    } 
}); 

這不是比你現在的jQuery更長的時間,並允許(理論上)的風格變化無窮數,而無需添加一百萬長if/else語句。要添加新的樣式更改,您必須在每個三個數組的末尾添加一個值。 stylePoints指定應在其中添加或刪除樣式的值爲scrollTop()styleTo指定要添加或刪除的類。 styleType指定當用戶滾動以上對應的stylePoints值時是否應該添加或刪除此類。當用戶滾動對應的stylePoints值時會出現相反的情況。例如,您可以從代碼中看到tall類將爲header中的removed,當用戶滾動到200以上時,並在用戶滾動到下方或200時添加。

+0

有沒有一種方法可以改進這個答案,所以它被接受? – SpyderScript