2011-02-01 34 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); 
}