Smooth Scrolling 跳的很奇怪
Smooth Scrolling jumps weirdly
$(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
}, 1000);
if (target.length <= 1000) {
$('html,body').animate({
scrollTop: target.offset().top - 60
}, 1000);
};
return false;
}
}});});
我正在使用一个固定的导航栏,屏幕最大宽度 < 1000 像素。
导航栏的高度为 60 像素。所以如果 max-with < 1000px.
它会向后移动 60px 动画
一切正常,但我的问题是只有当视口大于 1000px 时页面才会奇怪地跳转。
我认为问题在于您没有阻止默认的点击事件。这意味着浏览器会跳转到您想要的#id(因为这是浏览器的默认行为),然后平滑滚动会从头开始触发动画,从而实现快速跳转。
要修复它,只需使用 preventDefault();
阻止默认事件
快速示例:
$('selector').click(function(e) {
e.preventDefault();
// your code
});
固定代码:
$(function() {
$('a[href*=#]:not([href=#])').click(function(e) {e.preventDefault(); {
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
}, 1000);
if (matchMedia('only screen and (max-width: 1000px)').matches) {
$('html,body').animate({
scrollTop: target.offset().top - 60
}, 1000);
window.location.hash = '#' + target[0].id;
return false;
}
}
}
}
});
});
$(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
}, 1000);
if (target.length <= 1000) {
$('html,body').animate({
scrollTop: target.offset().top - 60
}, 1000);
};
return false;
}
}});});
我正在使用一个固定的导航栏,屏幕最大宽度 < 1000 像素。
导航栏的高度为 60 像素。所以如果 max-with < 1000px.
一切正常,但我的问题是只有当视口大于 1000px 时页面才会奇怪地跳转。
我认为问题在于您没有阻止默认的点击事件。这意味着浏览器会跳转到您想要的#id(因为这是浏览器的默认行为),然后平滑滚动会从头开始触发动画,从而实现快速跳转。
要修复它,只需使用 preventDefault();
快速示例:
$('selector').click(function(e) {
e.preventDefault();
// your code
});
固定代码:
$(function() {
$('a[href*=#]:not([href=#])').click(function(e) {e.preventDefault(); {
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
}, 1000);
if (matchMedia('only screen and (max-width: 1000px)').matches) {
$('html,body').animate({
scrollTop: target.offset().top - 60
}, 1000);
window.location.hash = '#' + target[0].id;
return false;
}
}
}
}
});
});