gpt4 book ai didi

javascript - 缓动平滑滚动不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 10:14:05 25 4
gpt4 key购买 nike

我有一个 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;
}
}
});
});

我做了一个JSFiddle以函数中的为例。 (我包含了 JQuery 缓动的代码)

JSFiddle 中有一个类似的函数然而,即使这个确实有效,它也不包括使用缓动的选项。如果能帮助解决问题,我将不胜感激

编辑

扩展我的意思是行不通的;单击链接时没有动画,它只是立即滚动到页面中的那个位置。

最佳答案

这里发生了一些非常奇怪的事情。

在下一行你使用了单双引号而不是两个单引号

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');

为了让 anchor 出现在页面上,我们简单地从函数中删除 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'});
});
});

关于javascript - 缓动平滑滚动不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com