jQuery滚动到.animate顶部 - 首先跳到底部? [英] jQuery scroll to top with .animate - jumps to bottom first?

查看:208
本文介绍了jQuery滚动到.animate顶部 - 首先跳到底部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下jQuery代码片段:

  $('html,body')。animate({
scrollTop :178
},2000);

我在页面底部有一些分页按钮,当它们被点击时触发一个javascript函数。在这个JS函数中,调用了上面的代码片段。



这很好地将页面回滚到菜单上方的顶部,但首先看起来页面跳到底部突然(除非你已经在最底部)滚动像它应该吗?



我正在撕裂我的头发,试图找出这种行为。

我不知道如何解释它除了提供一个链接到网站: http://tinyurl.com/apdloyl



一旦结果载入,转到页面底部,向上滚动稍微,然后点击下一页按钮。



感谢您的帮助。

解决方案

所以我的解决方案如下



我有一个容器div,#main,它的CSS高度为'auto' 。

当我的分页按钮被按下时,这个div的内容被擦除,并通过ajax替换为新内容。



我的修复方法是立即抓取将div的高度设置为固定格式的当前高度,滚动到顶部,然后一旦完成回滚,将div的高度重置为自动。



类似于:

  / *首先,我们必须修复#main元素的高度,以防止出现令人讨厌的混乱时ajax内容消失* / 
va r height = $('#main')。height();
$('#main')。height(height);
$ b $ *然后我们可以滚动到顶部* /
$('html,body')。animate({
scrollTop:178
},2000,函数(){

/ *然后将高度重置为自动* /
$('#main').css('height','auto');

});

可能还有其他更优雅的方法,但这对我很有用


I have the following jQuery snippet

$('html, body').animate({
    scrollTop: 178
}, 2000);

I have some pagination buttons at the bottom of the page, that trigger a javascript function when they are clicked. In this JS function, the above snippet is called.

This works fine to scroll the page back to the top just above the menu, but first of all the page seems to jump down to the very bottom abruptly (unless you are already at the very bottom) before scrolling up like it should?

I am tearing my hair out trying to figure this behaviour out.

I'm not sure how else to explain it apart from giving a link to the site: http://tinyurl.com/apdloyl

Go to the bottom of the page once the results have loaded, scroll up slightly, then click the next page button. And the weirdness happens as the page jumps down before scrolling back up.

Thanks for any help.

解决方案

So my solution was as follows

I had a container div, #main, which had a height of 'auto' set in CSS.

When my pagination button was pressed, the contents of this div were wiped and replaced with new content via ajax.

When the contents were removed, the browser window shrunk and as a result you were always bumped to the bottom of the page.

My fix was to immediately grab the height of the div, set it to it's current height in fixed format, do the scroll to the top, and then once the scrollback was complete reset the div's height to auto.

Something like:

/* First we have to fix the height of the #main element to prevent a nasty looking jerk                      when the ajax content dissapears */
var height = $('#main').height();
$('#main').height(height);

/* Then we can scroll to the top */
$('html, body').animate({
scrollTop: 178
}, 2000, function() {

    /* Then reset height to auto */
    $('#main').css('height','auto');

});

There are probably other more elegant ways of doing it but this works for me

这篇关于jQuery滚动到.animate顶部 - 首先跳到底部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆