繁体   English   中英

ajax调用后如何停止滚动到顶部

[英]How to stop scrolling to top after an ajax call

我使用 setInterval 函数更新 htm 元素的某些内容以每隔几秒调用一次 ajax

<div class="content">
<p>New informaton here</p>
<br>
<p>.......</p>
more information below
</div>

下面是javascript

var main = function(){
        updatingMessage = setInterval(function(){
         $.ajax({
        type: "POST",
        url:" call_MYSQLDatabase_To_Update_Content.php",
        cache:0,
        data:({
           some vars
             }),
        success:function(result){
         $(".content").html(result);
                          }
                 });  
                       }, 1000);
     updatingMessage();
        }
$(document).ready(main);

困扰我的是每次当我向下滚动查看信息时,它会在每次 ajax 调用后滚动到自身顶部。
在 ajax 调用之后是否仍然保持相同的<p>位置?

首先,您必须获取元素的滚动位置,然后通过将scrollTop属性设置为原始位置来确保保持该位置。

var position = element.scrollTop;

//do some work here, which might change the position

element.scrollTop = position;

就我而言,我有一个带有overflow-y: auto和固定height: 350px .scrollTop()函数不起作用。 事实上,我试图读取<table><tbody>的 Y 位置,但它总是返回0

当我刷新我的<table>时,浏览器会重置我的表格上的滚动位置! 我绝对需要防止这种情况。

这是我的解决方法:

  • 仅更新<tbody>的内容而不是整个<table>

它工作正常,我的表格的滚动位置没有重置。

下面是我的代码的一部分,它每 10 秒更新 3 个表:

function updateTables() {
    jQuery.ajax({
        url: '/get-tables.php',
        dataType: 'json',
        type: 'get',
        data: {
            tableId: [
                'table-actual',
                'table-new',
                'table-history'
            ]
        },
        success: function(response){
            jQuery.each(response, function (key, table) {
                jQuery('#table-' + table.id + ' tbody').html(data.content);
            });
        }
    }); 
}

setInterval(updateTables, 10000);

希望它对你们中的一些人有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM