设置scrollTop跨浏览器

rps*_*ep2 2 javascript

我在设置scrollTop跨浏览器时遇到问题。我进行了搜索,说要使用下面的解决方案。

我目前有:

var body = document.documentElement || document.body;
body.scrollTop = 200;
Run Code Online (Sandbox Code Playgroud)

这适用于IE,而不是Chrome

如果我把它转过来:

var body = document.body || document.documentElement;
body.scrollTop = 200;
Run Code Online (Sandbox Code Playgroud)

它适用于chrome,而不是IE

如何解决这个问题?

Phi*_*ucK 5

在这方面存在一些互操作性问题和不兼容性。为了避免用户代理嗅探(并简化向document.documentElement.scrollTop控制视口而不是的标准API的迁移document.body.scrollTop),现代浏览器中实现了新的API。基本上,有一个滚动功能可以做到这一点-

function scrollViewport(top, left)
{
 var eViewport = document.scrollingElement
 if (eViewport)
 {
  if (typeof top !== "undefined")
  {
   eViewport.scrollTop = top;
  }
  if (typeof left !== "undefined")
  {
   eViewport.scrollLeft = left;
  }
 }
 else
 {
  // Do your current checks or set the scrollLeft and scrollTop
  // properties of both of documentElement and body, or user agent
  // sniffing, if you must.

  // Example -
  // var scrollTop = 200;
  // Chrome, Internet Explorer and Firefox, I think.
  // document.documentElement.scrollTop = scrollTop;
  // Safari, at least up to version 11, I think.
  // document.body.scrollTop = scrollTop;
  // Or just (I am not sure I recommend this)...
  // window.scrollTo(0, scrollTop);
 }
}
Run Code Online (Sandbox Code Playgroud)

阅读Opera文章以获得更多信息。