fan*_*ncy 32 javascript jquery jquery-ui jquery-plugins
我正在将内容添加到身体的顶部.有时这个内容可以是400-500px高,当这样的内容被添加时,在你阅读页面时推下内容可能会非常烦人.
我想要自动添加项目,而不是点击此处查看新项目.
有没有办法在不移动页面的情况下将此内容添加到正文顶部?然后,当用户滚动到顶部时,它已经存在?
She*_*aff 39
我相信最常用的方法是在修改之前和之后简单地测量文档高度:
var old_height = $(document).height(); //store document height before modifications
var old_scroll = $(window).scrollTop(); //remember the scroll position
//do anything
$("p:first").prepend( "<p>I just became first</p>" );
$(document).scrollTop(old_scroll + $(document).height() - old_height); //restore "scroll position"
Run Code Online (Sandbox Code Playgroud)
这样你就可以在没有窗口远离你正在阅读的内容的情况下做任何事情:)
Gro*_*ain 17
我在过去通过预先添加元素,然后计算它们的总外部高度,并将scrolltop设置为该值来完成它.像这样的东西:
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);
Run Code Online (Sandbox Code Playgroud)
希望这能指出你正确的方向.
小智 9
我采取了一种略有不同的方法:
首先获取正文的第一个元素(或者如果你假装一个除了我需要的主体之外的元素,则获取另一个元素),然后在预先添加新的元素集之后,使用偏移量(如果需要滚动)相对于body)或原始第一个元素上的位置(如果需要相对于祖先元素滚动)函数以获取其更新的坐标并滚动到该点.
就像是:
var current_top_element = $('body').children().first();
$('body').prepend(other_elements);
$('body').scrollTop(current_top_element.offset().top);
Run Code Online (Sandbox Code Playgroud)
或者除了身体滚动之外的其他内容:
var current_top_element = $('#ul-element-id li:first'); //example with a list
$('#ul-element-id').prepend(other_elements);
$('#ul-element-id').scrollTop(current_top_element.position().top);
Run Code Online (Sandbox Code Playgroud)
请注意,position()返回元素相对于其偏移父元素的位置,因此请确保根据需要设置父元素的css position属性(http://api.jquery.com/offsetParent/)
有关更多详细信息,请访问:http: //api.jquery.com/category/offset/
小智 5
我知道,我很晚才讨论这个话题。很抱歉没有挖掘它,但我发现了一种非常简单的方法来防止在将元素添加到正文时滚动到顶部。
当滚动 Y 位置为零时,自动滚动附加。只需这样做:
element.scrollTo(0, 1);
Run Code Online (Sandbox Code Playgroud)
并且您的元素在前置后不会自动进入顶部。
| 归档时间: |
|
| 查看次数: |
13238 次 |
| 最近记录: |