【问题标题】:$.ajax call and getting/scrolling to top of div$.ajax 调用和获取/滚动到 div 顶部
【发布时间】:2014-10-10 12:23:49
【问题描述】:

我有一个由 ajax 调用填充的 div。我猜我不能 scrollTop() 到 div,因为 dom 的高度为 0。

如何在每次加载内容时动态获取 div 的顶部并滚动(动画)到顶部?

    $.ajax({
        cache: false,
        url: 'content/'+u+'/this.content.php',
        data: { 'data-set-id' : t},
        type: 'post',
        success: function(e) {
            $('#div .content').fadeOut(function() {
                $(this).html(e).fadeIn();                  

            });
            // scroll to top of the populated div
        },
        error: function(e) {
            // error 
        }
    }); // ajax

【问题讨论】:

  • Dom 总是在更改后更新,因此您可以使用标准方式进行更新

标签: javascript jquery html css ajax


【解决方案1】:

您可以在成功回调中使用此代码在内容加载后滚动到 div 的顶部。

var stop = $('#div .content').scrollTop(); $('html, body').animate({ scrollTop: stop }, 'slow');

我希望这会有所帮助!

【讨论】:

  • 暂时不起作用。滚动是带有溢出-y的内页div:滚动;
【解决方案2】:

$("#div").animate({scrollTop: "0px"}); 

不工作?

任何偶然发现这个的人,这是一个小提琴:

http://jsfiddle.net/2z3fx3j5/1/

<body>
    <div>Hello</div>
</body>

$(document).ready(function() {
    $("body").animate({scrollTop: "1000px"}, 2000);
    $("body").animate({scrollTop: "0px"}, 2000);
});

div {
    bordeR: solid 1px black;
    height: 2000px;
}

【讨论】:

  • 您要滚动的 div 是什么?
  • 除非您告诉我们结果 html 是什么样子,否则我们无法为您提供帮助...
  • 你是对的。我在错误的 div 上启动,你的答案是正确的。
【解决方案3】:

Mutation-Observers是处理手头问题的一种方式,在页面底部添加以下代码:

<script>
var target = $("#div .content");
// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
   mutations.forEach(function( mutation ) {
   var newNodes = mutation.addedNodes; // DOM NodeList
if( newNodes !== null ) { 
    // If there are new nodes added
      $('#div .content')animate({ scrollTop: 0 }, 'slow'); 
      }
   });    
});

// Configuration of the observer:
var config = { 
attributes: true, 
childList: true, 
characterData: true 
};

// Pass in the target node, as well as the observer options
observer.observe(target, config);
</script>

【讨论】:

    【解决方案4】:

    你可以这样做:

    success: function(e) {
                $('#div .content').fadeOut(function() {
                    $(this).html(e).fadeIn();
    
                 $('html, body').animate({
                              scrollTop: $(this).offset().top
                  }, 1000);                  
    
                });
    
            }
    

    【讨论】:

      【解决方案5】:

      通过在 $.ajax 之前重置 DOM 的内容来解决它

      $('#div .content').empty(); 
      $.ajax({
          cache: false,
          // ...
      });
      

      $('#div .content').html('loading...');
      $.ajax({
          cache: false,
          // ...
      });
      

      这个答案比 2017 年晚了七年 :)

      【讨论】:

        猜你喜欢
        • 2020-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多