0

我正在尝试创建一个可以反复使用的功能。我已经设置好了,所以如果链接指向页面上的一个 H2 ID,那么它将滚动到偏移量为 + 10px 的目标,然后淡入淡出箭头几次。但是如果链接指向#footer 元素,那么它应该向下滚动页面,然后一旦到达目标,它就会将背景颜色从蓝色变为浅蓝色几次,然后又变回蓝色。

用这个制作函数的最有效方法是什么?所以我不会一直重复代码?

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

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

4

1 回答 1

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 );
}
于 2011-02-01T18:36:46.300 回答