[英]jQuery scrollTop is incorrect by the height of a slideUp div
我有一系列新闻项目(准确地说是警报和公告),每个新闻项目都单独包装在自己的<div>
标签中,用于隐藏除页面加载标题以外的所有内容。 单击任何标题( h2
)后,单个项目的详细信息就会显示出来( slideDown
),其他任何未打开的项目slideUp
折叠起来( slideUp
)。 因此,一次只能看到一个新闻。 都好。
当窗口宽度等于或小于平板电脑大小(767px)时,我还将代码设置为scrollTop
到最近单击的div的顶部。 这仅部分起作用。
我知道问题出在哪里,但不知道解决方案。
问题是,当我单击其他新闻项时,它的scrollTop坐标将被自动关闭的div的高度关闭。 我已经敲了一下脑袋,解决方案可能很简单,但是我没有提出。
该页面位于此处: http : //northqueensviewhomes.com/announcement-test
请记住,使页面宽度小于767px并刷新(当您的页面足够小时,您会看到布局响应,然后单击一些顶部的警报项,最终您会看到其中一个滚动过高,甚至下降,而不是上升到$this
div的顶部。
这是我的jQuery:
if ($('#bboards').length) {
/* Page Load Cleanup */
$('.announcement_item h2 + div,.alert_item h2 + div').hide().removeClass('toggler');
$('.moreText').removeClass('hidden');
function hideAll() {
$('.announcement_item h2, .alert_item h2').removeClass('toggler').children('.moreText').fadeIn('fast').end().next('div').slideUp('fast');
}
$('.announcement_item h2,.alert_item h2').hover(function() {
$(this).css({
'cursor': 'pointer',
'color': '#BC2E34',
});
}, function() {
$(this).css({
'cursor': 'default',
'color': 'black',
});
}).click(function() {
if ($('.toggler').length) {
var previouslySelected = $('.toggler').parent('div').height();
alert(previouslySelected);
} else {
var previouslySelected = 0;
// alert(previouslySelected);
}
if ($(this).hasClass('toggler')) {
hideAll();
$('.toggler').removeClass('toggler');
$(this).children('.moreText').fadeIn('fast'); //this is the "click to read more… text on the link"
if ($(window).width() <= 767 {
$('html, body').animate({
scrollTop: ($(this).parent('div.well').offset().top - 13)
}, 2222, 'easeInOutExpo');
}
} else {
hideAll();
$(this).addClass('toggler').next('div').slideDown('fast', 'easeInOutQuad');
$(this).children('.moreText').hide(); //this is the "click to read more… text on the link"
if ($(window).width() <= 767) {
$('html, body').animate({
scrollTop: ($(this).parent('div.well').offset().top - 13)
}, 2222, 'easeInOutExpo');
}
}
});
} // <--- End if $('#bboards').length
您可以在页面上实时看到HTML。 我添加了一堆虚拟条目只是为了创建页面高度。
我敢肯定,我只需要将scrollTop延迟到slideUp
完成之前,但是同样,我不确定如何做。
您可以尝试两种相对简单的解决方案。
如您所说,第一个是延迟scrollTop动画:
setTimeout(function() { $('html, body').animate({ scrollTop: ($(this).parent('div.well').offset().top - 13) }, 2222, 'easeInOutExpo'); }, 200);
或者,您可以记录每个公告的初始位置,并在页面加载时隐藏它们的内容后发出警报。 将标为/* Page Load Cleanup */
部分更改为以下内容:
/* Page Load Cleanup */ $('.announcement_item h2 + div,.alert_item h2 + div').hide().removeClass('toggler'); $('.moreText').removeClass('hidden'); $('.announcement_item, .alert_item').each(function() { $(this).data("top", $(this).offset().top); });
这为每个公告提供了一个存储其初始位置的数据条目。 然后,每当需要设置scrollTop动画时,请执行以下操作:
$('html, body').animate({ scrollTop: ($(this).parent('div.well').data().top - 13) }, 2222, 'easeInOutExpo');
请注意,这仅在通知和警报的内容未更改的情况下才能很好地起作用。
我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.