我试图在窗口大小调整时更改我的 JavaScript,但似乎无法让它工作。我想要的唯一区别是,当窗口变得小于 768px 时,offset().top 从 -90 更改为 -60。
这是我到目前为止所拥有的:
$(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-90
}, 1000);
return false;
}
}
});
});
$(window).resize(function(){
if ($(window).width() <= 768){
$(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-60
}, 1000);
return false;
}
}
});
});
}
});
任何建议都会非常好!
谢谢
最佳答案
第一个点击事件处理程序 $('a[href*=#]:not([href=#])').click
每次运行 js 时都会绑定(bind)。
调整大小时,您将第二个处理程序附加到单击事件 - 它不会覆盖第一个处理程序 - 因此一个事件附加了两个事件处理程序。
我猜你想首先像 $('a[href*=#]:not([href=#])').off('click');
一样取消绑定(bind)第一个事件处理程序调整窗口大小,然后附加第二个窗口。
但是由于您只更改一小段代码,您宁愿编写:
$(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 - ( ($(window).width() <= 768) ? 60 : 90)
}, 1000);
return false;
}
}
});
});
注意scrollTop 行
关于Javascript 改变窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501574/