最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Deciding which to scroll, document.documentElement or document.body - Stack Overflow

programmeradmin0浏览0评论

I'm building a page which has to scroll with animation to certain positions when something happens.

I'm applying jQuery.animate to document.documentElement and it seems to work properly on Firefox and some versions of IE, while on Chrome and other versions of IE it has to apply to document.body to work.

Am I being an idiot here? What am I missing? And if I'm not, what is the proper way to detect which one to use?

I'm building a page which has to scroll with animation to certain positions when something happens.

I'm applying jQuery.animate to document.documentElement and it seems to work properly on Firefox and some versions of IE, while on Chrome and other versions of IE it has to apply to document.body to work.

Am I being an idiot here? What am I missing? And if I'm not, what is the proper way to detect which one to use?

Share Improve this question asked Mar 27, 2012 at 15:47 Igor K.Igor K. 7701 gold badge10 silver badges25 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

You're not an idiot, it has always been tricky, see ments here for example :)

As far as I remember, $('html, body').animate({scrollTop: '-=100'}) works in all major browsers now.

It appears that the safe way to do this is running the animation on document.documentElement, document.body and window at once. One will work for sure.

Even though this solution is hideously ugly, it works in most cases.

An easy to use plugin is scrollTo: http://demos.flesler./jquery/scrollTo/

otherwise you can typically use $(window).animate();

There are several very old methods (not standard but working in every browser): window.scroll (), window.scrollTo(), window.scrollBy() and other. See e.g. this MDN page for documentation: https://developer.mozilla/en-US/docs/DOM/Window.scroll

Note that while in Firefox or Chrome these methods just change scrollTop/scrollLeft and do not cause immediate scrolling (scrolling is delayed until javascript event handler returns), in Opera and IE these methods actually scroll the window immediately (which is not very good).

It would be so much better if all browsers could use the same element for scrolling though.

发布评论

评论列表(0)

  1. 暂无评论