我正在尝试滚动到 URL 中的 div。它可以是 21 个 ID 之一,例如:
url.com/test#lite1
url.com/test#lite2
url.com/test#lite3
我需要在页面加载时发生这种情况(用户来自电子书,应该看到他们点击的确切元素)。
这是我目前拥有的代码:
$(document).ready(function(){
$('a[href^="#"]').load(function() {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top -150
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
</script>
它不起作用,我认为这是因为这部分(我不知道我在这里做什么):
$('a[href^="#"]').load(function() {
我还希望它位于页面的中心(而不是像浏览器滚动到 div 时那样在顶部被 chop )。请让我知道这是否正确:
$target.offset().top -150
提前致谢!
最佳答案
window.location.hash
包含 URL 中的当前哈希值,因此请使用它。由于哈希已经在 URL 中(正如您所说,他们通过单击带有哈希的链接来访问页面),因此您不需要手动添加它。
尝试使用这个:
$(document).ready(function(){
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top-150
}, 900, 'swing');
});
使用 wordpress,似乎 $ 需要用 jQuery 替换,所以它出来:
jQuery(document).ready(function(){
jQuery('html,body').animate({
scrollTop: jQuery(window.location.hash).offset().top-150
}, 900, 'swing');
});
关于javascript - Jquery滚动以在页面加载时偏移目标div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33525293/