2012-01-30 27 views
0

在jQuery中我總是遇到很多雙重工作。我的意思是,我爲不同的div編寫相同的東西。jQuery自動化多個div的多個腳本

我有以下代碼:

var about = $('#about').offset().top - parseFloat($('#about').css('margin-top').replace(/auto/, 0)); 
var education = $('#education').offset().top - parseFloat($('#education').css('margin-top').replace(/auto/, 0)); 
var work = $('#work').offset().top - parseFloat($('#work').css('margin-top').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 >= about) { 
     // if so, ad the fixed class 
     $('#nav li').removeClass('current'); 
     $('.ab_about').addClass('current'); 
    } else { 
     // otherwise remove it 
     $('.ab_about').removeClass('current'); 
    } 

    // whether that's below the form 
    if (y >= education) { 
     // if so, ad the fixed class 
     $('#nav li').removeClass('current'); 
     $('.ab_education').addClass('current'); 
    } else { 
     // otherwise remove it 
     $('.ab_education').removeClass('current'); 
    } 

    // whether that's below the form 
    if (y >= work) { 
     // if so, ad the fixed class 
     $('#nav li').removeClass('current'); 
     $('.ab_work').addClass('current'); 
    } else { 
     // otherwise remove it 
     $('.ab_work').removeClass('current'); 
    } 

}); 

你可以說,如果我有這些項目的20,這會是一個很長的腳本:P 任何想法上如何實現事物自動化並使其更小。我用.each方法嘗試了一些東西,但這對我來說是死路一條。

回答

3

U可以只創建一個簡單的插件,該插件分配給像這些div:

$.fn.myplugin = function(options){ 
    var $this = $(this); 
    var $navli = $(options.navli); 
    var $abClass = $(options.abClass); 
    var offset = $this.offset().top - parseFloat($this.css('margin-top').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 >= offset) { 
      // if so, ad the fixed class 
      $navli.removeClass('current'); 
      $abClass.addClass('current'); 
     } else { 
      // otherwise remove it 
      $abClass.removeClass('current'); 
     } 
    } 
} 

$(document).ready(function(){ 
    $('#about').myplugin({'navli': '#nav li', 'abClass': '.ab_about'}); 
}); 
+0

工程就像一個魅力,謝謝! :) – 2012-01-30 22:40:41

+0

不用擔心隊友:) – sally 2012-01-30 22:42:39

0

我不知道你想做什麼,但是從它的外觀,你可能不應該使用JS來實現它。

無論如何,簡化它的最好方法是創建一個jQuery插件。類似這樣的:

$.fn.fixStuff = function() { 
    return this.each(function() { 
     var $this = $(this); 
     return $this.offset().top - parseFloat($this.css('margin-top').replace(/auto/, 0)); 
    }); 
}; 

$('#about, #edutcation, #work').fixStuff(); 
+0

你有什麼建議我應該使用? – 2012-01-30 22:24:31

+0

就像我說的。我不知道你想要做什麼,但JS似乎有點駭人聽聞。我不知道在你的情況下是否可能,但JS黑客應該永遠是最後的選擇。我嘗試儘可能地使用CSS。不過,你可能會發現這個jQuery插件很有用:http://imakewebthings.github.com/jquery-waypoints/ – 2012-01-30 22:31:05

+0

你是對的,我也確實檢查過這個插件。我在做什麼:當我向下滾動頁面(用鼠標滾輪)時,我想動態地突出顯示當前菜單項與它的錨點div的關係。爲了做到這一點,我必須知道div的頂部偏移量。如果用戶滾動到下一個div,則應突出顯示下一個菜單項。 – 2012-01-30 22:40:10