【问题标题】:scrolling to the parent div top with jquery使用 jquery 滚动到父 div 顶部
【发布时间】:2013-10-24 21:52:26
【问题描述】:

我认为这很容易。

我有以下 HTML

<div>
<div id="child"></div>
</div>

我尝试了几件事

if ($('#child').length){
    $('html, body').animate({scrollTop: $(this).parent().offset().top}, 'slow');
}

if ($('.success_div').length){
    pdiv = $(this).parent();
    $('html, body').animate({scrollTop: pdiv.offset().top}, 'slow');
}

错误:TypeError:pdiv.offset(...) 未定义

【问题讨论】:

    标签: jquery jquery-animate scrolltop


    【解决方案1】:

    这个怎么样?

    if ($('#child').length){
        $('body').animate({scrollTop: $('#child').parent().offset().top},'slow');
    });
    

    在 if 语句中调用元素不会选择它,所以 $(this) 不匹配 if ($('#child').length){ 内部的任何内容,所以我在语句内部再次调用了 $('#child')

    【讨论】:

      【解决方案2】:

      将子元素滚动到父元素的顶部。

      if($('#child').length)
      {
        $('#parent').animate({
          scrollTop: $('#child').offset().top - $('#parent').offset().top
        },'slow');
      };
      

      【讨论】:

        猜你喜欢
        • 2017-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 1970-01-01
        相关资源
        最近更新 更多