Javascript 单击特定链接时,将不同的偏移设置为scrolltop
我现在有下面的代码,它工作得很好,当点击链接时会滚动到div的顶部Javascript 单击特定链接时,将不同的偏移设置为scrolltop,javascript,jquery,Javascript,Jquery,我现在有下面的代码,它工作得很好,当点击链接时会滚动到div的顶部 $(function () { $('a[href*=#]:not([href=#])').click(function () { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target =
$(function () {
$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({scrollTop: target.offset().top}, 1500);
return false;
}
}
});
});
然而,我想做的是,当点击一组特定的链接(#topbannerlinks a)时,它会滚动到div的顶部,但偏移量不同,例如
$("#topbannerlinks a").click(function(){
$('html,body').animate({ scrollTop: target.offset().top -180 }, 1500);
});
我能否以某种方式将build这个函数/if语句添加到上面的第一个函数中
我之所以这样做是因为我在目标链接页面上有不同的高度标题,并且它不能正确地滚动到顶部。您可以使用
.is()
检查某个元素是否与另一个选择器匹配。例如,如果您的链接也与#topBanner a
匹配,则返回true;如果是另一个链接,则返回false:
$(myLink).is('#topBanner a');
因此,在.click()
函数中,您可以使用$(this).is(“#topBanner a”)
执行此检查
与在代码中两次使用相同的animate
功能不同,您只需根据链接是否位于#topBanner
中设置偏移量,然后始终添加偏移量(无论是0还是180)
if (target.length) {
// set 180 if link is in #topBanner, otherwise 0
var offset = $(this).is('#topBanner a') ? 180 : 0;
$('html,body').animate({scrollTop: target.offset().top - offset}, 1500);
return false;
}