javascript - 为什么我的 anchor 标签滚动不流畅?

标签 javascript html

我已经在头部添加了这个

<script type="text/javascript" src="js/index.js"></script>

这是导航到“id="fillerSix"”div 标签的链接。

<h1><a href="#fillerSix">Mohammad Usman Khan</a></h1>

这是链接应该导航到的 id="fillerSix"。

<div id="fillerSix" class="fillerSix">

这是我的 index.js 文件

<script type="text/javascript">
$('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);
            return false;
        }
    }
});
</script>

该链接有效,因为它将用户定向到 anchor 但没有平滑滚动。

最佳答案

您在 index.js 中的区 block 应该包裹在 $(document).ready( function(){ /* your code here */ }); 中如上面的 DanielD 所示。

同样你不需要<script></script> .js 内的标签文件。这将导致解析错误。

index.js的新内容| :

$(document).ready( 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);
                return false;
            }
        }
    });
});

关于javascript - 为什么我的 anchor 标签滚动不流畅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967595/

相关文章:

javascript - 从 Firebase 数据库填充 Firebase Cloud Functions 中的数组

javascript - NextJS - onClick 时调用 js 函数

javascript - 获取输入内的点击字符位置(不是坐标)

javascript - 如何将动画保留在背景中,在另一个元素后面?

html - 固定元素问题 - 无法使其可滚动

javascript - 尝试创建 JQuery 弹出窗口重定向到另一个弹出窗口

javascript - FormData 不会传回 MVC Controller

javascript - 如何使用socket.io实现生存时间

jquery - 折叠切换时删除类

python - 使用 beutifulsoup 和 Mechanize 从 html 表中获取文本时出错