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
speed = 1500
显然,我需要一些帮助来实现此功能,或者如果您认为可以使其比上面的小示例更有效,请分享。
I'm trying to create a function that i can use over and over. I have it set up so if the link points to an ID on the page that is an H2, then it will scroll to the target with an offset of + 10px, then fade an arrow in and out a few times. But if the link points to the #footer element, then it should scroll down the page, then once landing at the target it changes the background color from a blue to a light blue a few times, then back to blue.
What would be the most efficient way to make a function with this? So i don't keep repeating code?
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.
using some of my code above, something like this, i think...:
function scrollToAnimate (ifTargetIsThis, yOffset, speed, callback)
ifTargetIsThis = #foot_Wrapper
yOffset = - $(window).height() + 139
speed = 1500
Obviously i need some help making this function, or if you think you could make it more efficient than my little example above, please share.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这相当简单,您可能想得太多了:
请注意,我将
ifTargetIsThis
排除在参数之外,因为我认为这仍然应该发生在函数外部,您可以这样调用:This is fairly straightforward, you're probably overthinking it:
Notice I left the
ifTargetIsThis
out of the arguments because I think that should still happen outside the function, which you would call like so: