我有一个JQuery
功能,可以通过JQuery
缓动来平滑滚动,但它不起作用,我似乎无法找到错误。
该功能的代码是
$(function(){
$('a[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) {
var targetOffset = $target.offset().top;
$(‘html,body’).animate({scrollTop: targetOffset}, {duration:1600,easing:'easeInBounce'});
return false;
}
}
});
});
我用函数in JSFiddle做了一个例子。 (我包含了JQuery
缓动的代码)
这是JSFiddle中的类似函数,但即使这个函数有效,它也不包括使用缓动的选项。我将非常感谢您解决问题的任何帮助
修改
扩展我的意思,它不起作用;单击链接时没有动画,它只是立即滚动到页面中的那个位置。
答案 0 :(得分:1)
你有一些非常奇怪的事情发生在这里。
在以下行中,您使用的是单引号而不是两个单引号
if (location.pathname.replace(/^\//,”) == this.pathname.replace(/^\//,”) && location.hostname == this.hostname) {
在此行中,您使用的不是单引号字符
$(‘html,body’).animate()
最后我们得到了这个。 jsFiddle
$(function(){
$('a[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) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, {duration:1600,easing:'easeInBounce'});
return false;
}
}
});
});
修改强>
要在此回答的评论中回答您的问题,要使“#”链接生效,我们会将您的$target =
行更改为此
$target = $target.length ? $target : $('html');
要让锚点显示在页面上,我们只需从函数中删除return false;
即可。在使用代码后,我将其缩减为:
$(function () {
$('a[href*="#"]').click(function () {
var $target = $(this.hash);
$target = $target.length ? $target : $('html');
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, {duration: 1600, easing: 'easeInBounce'});
});
});
答案 1 :(得分:0)
单击链接后,上面会出现一个解决方案的尖峰,然后向下移动,然后平滑滚动。对于那些与我有相同问题的人,您可以使用此版本,效果更好
// Smooth scrolling using jQuery easing with other links
$('a[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 - 54)
}, 1000, "easeInOutExpo");
return false;
}
}
});