jQuery自动化多个div的多个脚本

问题描述:

在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方法尝试了一些东西,但这对我来说是死路一条。

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

我不知道你想做什么,但是从它的外观,你可能不应该使用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