正在尝试将Top滚动到服务器端呈现的ID哈希位置



我有一个服务器端代码,它附加了一个ID作为ID属性。然而,当我将ID附加到URL并尝试滚动到它时,它会进行动画,但不会滚动到正确的ID。我搜索了多个线程,但它们都有相同的答案,我不明白为什么它不起作用。

任何帮助都将不胜感激,谢谢。

$(document).ready(function () {
setTimeout(function () {
var selector = $('.tab-panels li.active');
if (selector.hasClass('active')) {
var panelToShow = $(selector).attr('rel');
$('#' + panelToShow).toggle(function () {
$(this).addClass('active');
});
var hash = url.split('#').pop();
history.pushState(null, null, '?' + panelToShow + '#' + hash);
var target = '#' + hash;
console.log(target);
$('html, body').animate({
scrollTop: $(target).offset().top
}, 1000);
$(this).addClass('active').siblings().removeClass('active');
} else {
var selector = $('.tab-panels li:nth-of-type(1)');
var panelToShow = $(selector).attr('rel');
$('#' + panelToShow).toggle(function () {
$(this).addClass('active');
});
var url = location.hash;
var hash = url.split('#').pop();
console.log(hash);
history.pushState(null, null, '?' + panelToShow + '#' + hash);
var target = '#' + hash;
console.log(target);
$('html, body').animate({
scrollTop: $(target).offset().top
}, 1000);
$(selector, this).addClass('active').siblings().removeClass('active');
}
}, 100);
});

HTML

<div class="user-profile-post-actual" id="profile-post-{{ $profilePost->id }}">
</div>

首先将setTimeout移动到加载数据下方。

$(document).ready(function () {
var selector = $('.tab-panels li.active');
if (selector.hasClass('active')) {
var panelToShow = $(selector).attr('rel');
$('#' + panelToShow).toggle(function () {
$(this).addClass('active');
});
var url = window.location.hash;
var hash = url.split('#').pop();
console.log(hash);
history.pushState(null, null, '?' + panelToShow + '#' + hash);
var target = window.location.hash;
//console.log(target);
//$('html, body').animate({
//    scrollTop: $(window.location.hash).offset().top
//}, 1000);
//$(document).scrollTop($(window.location.hash).offset().top);
//$.scrollTo(window.location.hash);
document.getElementById(hash).scrollIntoView();
$(this).addClass('active').siblings().removeClass('active');
} else {
var selector = $('.tab-panels li:nth-of-type(1)');
var panelToShow = $(selector).attr('rel');
$('#' + panelToShow).toggle(function () {
$(this).addClass('active');
});
var url = window.location.hash;
var hash = url.split('#').pop();
console.log(hash);
history.pushState(null, null, '?' + panelToShow + '#' + hash);
var target = window.location.hash;
//console.log(target);
//$('html, body').animate({
//    scrollTop: $(window.location.hash).offset().top
//}, 1000);
//$(document).scrollTop($(window.location.hash).offset().top);
//$.scrollTo(window.location.hash);
document.getElementById(hash).scrollIntoView();
$(selector, this).addClass('active').siblings().removeClass('active');
}
setTimeout(function () {
//document.getElementById(hash).scrollIntoView();
//$.scrollTo(window.location.hash);
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000);
}, 1000);
});

最新更新