jQuery $('html, body').animate 和 $('body').animate 之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19303405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:37:16  来源:igfitidea点击:

difference between $('html, body').animate and $('body').animate?

javascriptjquery

提问by Lior

For example, to scroll to a certain element on the page (ie here: How to go to a specific element on page?)

例如,滚动到页面上的某个元素(即这里:如何转到页面上的特定元素?

$("#fromTHIS").click(function() {
    $("html, body").animate({ scrollTop: $("#toTHIS").offset().top }, 500);
    return true;
});

I've tried both and they both look that they are doing the job. What am I missing?

我已经尝试了两者,他们看起来都在做这项工作。我错过了什么?

采纳答案by Joe

The reason you use a selector for BOTH $('html, body')is because of web browser inconsistency. After a few tests I have found three things:

您对 BOTH 使用选择器的$('html, body')原因是 Web 浏览器不一致。经过几次测试,我发现了三件事:

  1. The browsers Firefox& IEutilize the html portion of this selector
  2. Browsers in the "webkit class" eg: Safariand Chromerespond to the body.
  3. Although one can avoid the issue all together by using $(document)instead.
  1. 浏览器Firefox&IE利用此选择器的 html 部分
  2. “webkit 类”中的浏览器例如:SafariChrome响应正文。
  3. 虽然可以通过使用$(document)来避免这个问题。

There's also a ticket on the jQuery bug tracker specifically stating this issue here

jQuery 错误跟踪器上还有一张票,专门在此处说明了此问题

回答by evilReiko

$('html, body')seems to be the jquery solution for cross-browser scroll animation.

$('html, body')似乎是跨浏览器滚动动画的 jquery 解决方案。

If you want a cross browser solution without animation, you can go ahead and try this:

如果你想要一个没有动画的跨浏览器解决方案,你可以继续尝试这个:

$(window).scrollTop(0);
// Accepts int of pixels.

Tested it on latest Chrome, Opera and FF. Seems to work cross browser. (Unless someone can confirm that it doesn't work on IE or Safari or others)

在最新的 Chrome、Opera 和 FF 上对其进行了测试。似乎可以跨浏览器工作。(除非有人可以确认它不适用于 IE 或 Safari 或其他)

Read more about jQuery scrollTop.

阅读有关 jQuery scrollTop 的更多信息。

回答by Arjjun

Here is an example for cross browser animation:

这是跨浏览器动画的示例:

//('html, body') is the jquery solution for cross browser scroll animation $('html, body').animate({ scrollTop: $(".abc-container").offset().top+ "-50px" }, 300)

//('html, body') is the jquery solution for cross browser scroll animation $('html, body').animate({ scrollTop: $(".abc-container").offset().top+ "-50px" }, 300)