javascript - 在页面加载时平滑滚动到所需的部分

标签 javascript jquery html css wordpress

我创建了一个带有自定义分页功能的 WordPress 网站。该函数将#latest 添加到链接的末尾,以将最新帖子定位到我的网站div。例如,如果用户单击第3 页,它将加载该页面,然后将它们发送到div #latest。这工作正常,但我希望它能顺利滚动到 div。

我尝试添加这个 jQuery 但没有任何反应,它仍然只是突然转到该部分。

jQuery(document).ready(function(){
    jQuery('a[href^="#"]').on('load',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        jQuery('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

有更好的方法吗?

最佳答案

我相信当滚动动画生效时,有一些资源没有被考虑在内,因为该功能是通过顶部偏移来工作的——你必须确保在所有可能影响的资源之后你正在使用它正在加载文档的高度或元素的偏移量。

ready 更改为 load

.ready() vs. .load()

In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

这是我的功能:

$(function(){
    var target = "latest";
    $('html, body').animate({
        scrollTop: $('#'+target).offset().top
    }, 900,'swing');
    return false;
});

JSFiddle

关于javascript - 在页面加载时平滑滚动到所需的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33347539/

相关文章:

javascript - 为什么即使设置了操作 URL 后,表单仍被发布到错误的 URL?

javascript - 为什么我的变量在循环时不可迭代

html - 悬停时带动画箭头的线

javascript - Vega-Lite - 如何组合线条和符号图例

javascript - angularjs从ng-repeat获取一个对象到不同页面中的 Controller

javascript - AEM 中 TouchUI RTE 中的多个自定义插件无法正常工作

javascript - 如何在 jquery 自动完成中绑定(bind)按键事件?

javascript - 在变量 jquery 中运行 .hover()

html - 三列布局中的 CSS 中心元素

html - 电子邮件模板的响应HTML页面?