jQuery:これを関数に変えますか?オプションのオフセットと速度などでボディを#IDにスクロールする
質問
何度も使用できる関数を作成しようとしています。セットアップしているので、リンクが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
yoffset = - $(window).height() + 139
速度= 1500
明らかに、この機能を作成するヘルプが必要です。または、上記の私の小さな例よりも効率的にできると思われる場合は、共有してください。
解決
これはかなり簡単です、あなたはおそらくそれを考えすぎています:
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 );
}
所属していません StackOverflow