设置scrollTop跨浏览器

set scrollTop cross browser

本文关键字:浏览器 scrollTop 设置      更新时间:2023-09-26

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

我目前有:

var body = document.documentElement || document.body;
body.scrollTop = 200;

这适用于IE,而不是chrome

如果我把它转过来:

var body = document.body || document.documentElement;
body.scrollTop = 200;

它在chrome中工作,而不是IE

如何解决这个问题?

这方面存在一些互操作性问题和不兼容性。为了避免用户代理嗅探(并便于迁移到标准的API,其中document.documentElement.scrollTop控制视口,而不是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);
 }
}

阅读Opera文章了解更多信息。

使用

var body = document.documentElement;
body.scrollTop = 200;

它应该是跨浏览器的,除非你做错了什么,比如丢失了html标签或类似的东西。

参考