2011-02-01 20 views
0

我试图创建一个函数,我可以反复使用。如果链接指向页面上的H2是一个ID,那么它将滚动到目标,偏移量为+ 10px,然后淡入淡出几次。但是,如果链接指向#footer元素,那么它应该向下滚动页面,然后一旦着陆目标,它会将背景颜色从蓝色变为浅蓝色几次,然后再变回蓝色。Jquery:把它变成一个函数?滚动身体#id与可选的偏移和速度等

什么是最有效的方式来做出这个功能?所以我不会重复代码?使用

var target = $(this).attr("href"); ............... 
     if ($(target).is('#foot_wrapper')) { 
      $('html,body').delay(600).animate({ 
        scrollTop: $(target).offset().top - $(window).height() + 139 
      }, 1500, function() { 
       $('#bottomline').animate({ 
        backgroundColor: "#2f5e9f" 
       }, 300).animate({ 
        backgroundColor: "#76acfb" 
       }, 300) 

      }) 
     } else if ($(target).is('#header')) { etc. etc. etc. 

一些我上面的代码,这样的事情,我觉得...:

function scrollToAnimate (ifTargetIsThis, yOffset, speed, callback) 

ifTargetIsThis = #foot_Wrapper

Y偏移= - $(window).height() + 139

速度= 1500

显然我需要一些帮助做这个功能,或者如果你认为你可以使它比我上面的小示例更有效率,请分享。

回答

1

这是相当简单的,你得太多可能是:

var scrollToAnimate = function (yOffset, speed, callback) { 
    $('html,body').delay(speed*0.4).animate({ 
    scrollTop: $(target).offset().top + yOffset 
    }, speed, callback}); 
} 

通知我离开了ifTargetIsThis出来的论据,因为我认为还是应该发生的功能,你会打电话像这样外:

if ($(target).is('#foot_wrapper')) { 
    scrollToAnimate(-$(window).height() + 139, 1500, function() { 
    $('#bottomline').animate({backgroundColor: "#2f5e9f"}, 300) 
        .animate({backgroundColor: "#76acfb"}, 300); 
    }); 
} else if ($(target).is('#header')) { 
    scrollToAnimate(etc, etc, etc); 
}