【问题标题】:ownerDocument error when using jQuery's scrollTop & animate functions使用 jQuery 的 scrollTop 和动画函数时的 ownerDocument 错误
【发布时间】:2012-06-01 08:04:55
【问题描述】:

我偶然发现了一个非常奇怪的错误。我正在使用 jQuery scrollTop 让窗口滚动到 .extrasWarning 类的位置,只要该类不在窗口的视线范围内。这是以下代码:

$('[data-required] .number select').change(function () {
var number = $(this).closest('.choice_data').data('required'),
windowPos = $(window).height(),
selectedAmount = 0;
alert(windowPos);
$(this).closest('.choice_data').find('.number option:selected').each(function (i) {
  selectedAmount = selectedAmount + parseInt($(this).val());
});
if (selectedAmount > number) {
  $(this).closest('.choice_data').next('.extrasWarning').show();
  var errorPos = $(this).closest('.choice_data').next('.extrasWarning').offset().top;
  alert(errorPos);
  if (errorPos > windowPos) {
    $(window).animate({
      scrollTop: errorPos
    }, 1000);
  }
} else {
  $('.extrasWarning').hide();
}
});

当我使用元素选择另一个选项时,所有事件都会正常触发,除了 $(window).animate 函数。 FireFox 显示以下错误:a.ownerDocument 未定义。

问题在于将 animate 函数与 scrollTop 函数结合使用。如果我实施以下更改:

if (errorPos > windowPos) {
  $(window).scrollTop(errorPos);
}

它突然工作正常!但是,我真的很想使用动画功能。知道我怎样才能做到这一点吗?谢谢!

【问题讨论】:

    标签: jquery window jquery-animate undefined scrolltop


    【解决方案1】:

    尝试动画 body 和 html 元素:

      if (errorPos > windowPos) {
        $("body, html").animate({
          scrollTop: errorPos
        }, 1000);
      }
    

    【讨论】:

    • 不幸的是不起作用。使用 $(document) 时,FireFox JS 控制台显示以下错误:a.ownerDocument 为 null。这次不是“未定义”。
    • @MartijnvanTurnhout 尝试 html 和 body 元素。
    • “html 和正文”组合效果很好!你的投票即将到来!
    【解决方案2】:

    $(elem).animate 动画 CSS 属性,并且滚动位置不是一个。 不正确;如果给定的属性不是 CSS 属性,jQuery 会将其视为元素属性。

    无论如何,animate 没有 dom 元素有一个不太为人所知的用途,而是为你喜欢的任何值设置动画:

    var jWin = $(window);
    var currentPos = jWin.scrollPos();
    $({pos: currentPos}).animate(
        {pos: errorPos},
        {
            duration: 1000,
            step: function () { jWin.scrollTop(this.pos) },
            complete: function () { jWin.scrollTop(errorPos); }
        }
    );
    

    这会将pos 从当前滚动位置动画到预期目标errorPos。在step 函数中,您可以相应地设置实际滚动位置。

    complete 步骤是必要的,因为 step 通常不会使用最终值调用。

    【讨论】:

    • scrollTop 与动画功能配合得很好!我不得不使用 'html, body' 而不是 'window' 选择器。就是这样。但无论如何感谢您的输入! :)
    • 是的,“它只为 CSS 设置动画是错误的”,jQuery 再一次比我聪明;p 你只需要动画对象和实际的 dom 元素(windowdocument 都不是)。
    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2016-08-12
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多