gpt4 book ai didi

javascript - 设置 scrollTop 跨浏览器

转载 作者:行者123 更新时间:2023-11-29 18:16:02 25 4
gpt4 key购买 nike

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

我目前有:

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

这适用于 IE,不适用于 chrome

如果我换个 Angular :

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

它适用于 chrome,不适用于 IE

如何解决这个问题?

最佳答案

这方面存在一些互操作性问题和不兼容性。为了避免用户代理嗅探(并简化向标准 API 的迁移,其中 document.documentElement.scrollTop 控制视口(viewport),而不是 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 article获取更多信息。

关于javascript - 设置 scrollTop 跨浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23313092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com