我创建了一个带有自定义分页功能的 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
。
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;
});
关于javascript - 在页面加载时平滑滚动到所需的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33347539/