jQuery .scrollTop()无法正常工作 [英] Jquery .scrollTop() not working

查看:1365
本文介绍了jQuery .scrollTop()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了我的问题. 所以这是我的代码:

The title explains my problem. So here's my code:

$("#my-div ul").scrollTop($("#my-div ul")[0].scrollHeight);

#my-div使用AJAX填充.因此,在我的ajax请求中,我获得了一个成功回调,该回调执行上述代码:

#my-div get filled using AJAX. So in my ajax request, I've got a success callback which performs the above code:

$.ajax({
    url: 'getLog.php',
    data: {'logFile': 'log.php'}, // echo "<ul> A BUNCH OF <li>s here </ul>"
    success: function(data){
        $("#my-div").html(data);
        // console.log($("#my-div ul")[0].scrollHeight); // Debugging Purposes
        $("#my-div ul").scrollTop($("#my-div ul")[0].scrollHeight);
    }
});

我继续进行操作,并在控制台上记录了$(#my-div ul")[0] .scrollHeight(如您在代码中所见),以查看它在执行.scrollTop()之前是否知道scrollHeight,并且工作正常(它显示为720,然后我增加了日志文件的大小,然后刷新,显示为830)

I went ahead and console logged $("#my-div ul")[0].scrollHeight (As you can see in the code) to see if it knows the scrollHeight before performing .scrollTop() And it worked (It showed 720 Then i increased the size of the log file, and then i refreshed, it showed 830)

令人惊讶的是,当我进入控制台(Chrome)并输入

The surprising thing is, when i goto the console (Chrome) and enter

$("#my-div ul").scrollTop($("#my-div ul")[0].scrollHeight);

它运行完美,并且ul一直滚动到底部!

It works perfectly, and the ul scrolls all the way to the bottom!

我不知道为什么它不起作用...:(

I can't figure out why it's not working though... :(

推荐答案

更改HTML时,浏览器不会重新呈现所有内容,因此始终存在很小的间隔.如果没有间隔,则JavaScript执行会阻止浏览器并且用户无法使用您的页面(按预期方式). <-这可能是原因:)

Browser do not re-render all content when the HTML is changed, there is always a small gap.If there was no gap the javascript execution would block the browser and the user couldn't use your page (as intended). <- This could be the reason :)

您可以尝试:

$.ajax({
url: 'getLog.php',
data: {'logFile': 'log.php'}, // echo "<ul> A BUNCH OF <li>s here </ul>"
success: function(data){
    $("#my-div").html(data);
    // console.log($("#my-div ul")[0].scrollHeight); // Debugging Purposes
    setTimeout(function() {
       $("#my-div ul").scrollTop($("#my-div ul")[0].scrollHeight);
    }, 10);
}
});

如果这是问题所在,您还可以尝试将setTimeout内的时间降低为0-它将不是0,而是每个浏览器设置的最短时间.

If that was the problem you can also try to lower the time inside setTimeout to 0 - it will not be 0 but the minimal time each browser sets.

这篇关于jQuery .scrollTop()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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