javascript - 平滑滚动+按钮 'onclick' 功能

标签 javascript html css

我正在使用以下 js 实现页面内页面 anchor 的平滑滚动:

$(document).ready(function() {
        $("a").on('click', function(event) {
            if (this.hash !== "") {
                event.preventDefault();
                var hash = this.hash;
                $('html, body').animate({
                    scrollTop: $(hash).offset().top
                }, 800, function() {
                    window.location.hash = hash;
                });
            }
        });
    });

在我想使用按钮 + 链接之前,它工作正常。例如,我有一个按钮:

<button onclick="location.href='#anchor'" class="button">Name</button>

我尝试使用上面的函数,比如将 $("a")... 更改为按钮中的类或 id,即 $(".button")... 但事实并非如此做任何事情。不幸的是,我的 js 知识到此为止。有谁知道这是否可能?谢谢!

最佳答案

问题是您正在立即更改按钮中的 href。

试试这个:

<button data-hash="anchor" class="button" type="button">Name</button>

$(document).ready(function() {
    $("button.button").on('click', function(event) {
        var hash = $(this).data("hash");
        if (hash) {
            $('html, body').animate({
                scrollTop: $(document.getElementById(hash)).offset().top
            }, 800, function() {
                window.location.hash = hash;
            });
        }
    });
});

关于javascript - 平滑滚动+按钮 'onclick' 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50648559/

相关文章:

html - DIV适合父级的宽度内容

javascript - 如何找出阻止点击发生的原因?

html - 修复了移动浏览器上的 header 问题

javascript - Mopub 移动网络/javascript 实现调整文本大小/覆盖 CSS

javascript - 当我用 jquery 将鼠标悬停在图像上时,如何使跨度保持不变?

javascript - 使用POST方法给用户授权::Angular2&TypeScript

javascript - 如何删除一个 “input type=file”倍数的具体值

javascript - 从创建文本字段的下拉列表中选择 'OTHERS' 选项 Ruby on Rails - 4.2

css - 样式选项标签

javascript - 在 popup.js 中创建链接并使其在 popup.html 中可点击