如何防止在前面滚动?

我将内容添加到正文的顶部.有时,此内容可能有 400-500 像素高,当添加此类内容时,在阅读页面时将内容向下推会非常烦人.

I'm prepending content to the top of the body. Sometimes this content can be 400-500px tall, and when something like this gets added, pushing the content down when you are reading the page it can be really annoying.

我希望自动添加项目,而不是单击此处查看新项目.

I want the items to be automatically prepended, not something like click here to see new items.

有没有办法在不移动页面的情况下将此内容添加到正文顶部?那么当用户滚动到顶部时它就已经在那里了?

Is there any way to prepend this content to the top of the body without moving the page? Then when a user scrolls to the top it is just there already?

推荐答案

我过去通过预先添加元素,然后计算它们的总外高,并将滚动顶部设置为该值来完成此操作.像这样的:

I've done it in the past by prepending the elements, then calculating their total outerheight, and setting the scrolltop to that value. Something like this:

var $current_top_element = $('body').children().first();
$('body').prepend(other_elements);

var previous_height = 0;
$current_top_element.prevAll().each(function() {
  previous_height += $(this).outerHeight();
});

$('body').scrollTop(previous_height);

希望这会为您指明正确的方向.

Hope this points you in the right direction.

相关文章