[英]Why body.scrollTop is not working on Google chrome and Firefox but working on Microsoft edge
[英]window.top.document.body.scrollTop not working in Chrome or FireFox
我有下面的代碼將打開一個模式窗口。 這適用於 IE 8,但不適用於 Chrome 或 FF。 我是跨瀏覽器功能世界的新手。
function ShowModal(WindowID,FramesetID)
{
window.onscroll = function () { window.top.document.getElementById(WindowID).style.top = window.top.document.body.scrollTop; };
window.top.document.getElementById(WindowID).style.display = "block";
window.top.document.getElementById(WindowID).style.top = document.body.scrollTop;
widthv=parseInt(parseInt(screen.width)/1.50);
heightv=parseInt(parseInt(screen.height)/1.50);
window.top.document.getElementById(FramesetID).style.width=widthv;
window.top.document.getElementById(FramesetID).style.height=heightv;
}
任何人都可以幫助使此代碼與 Chrome 和 FF 兼容嗎?
我嘗試將window.top
更改為window.parent
但沒有運氣另外,在為多個瀏覽器編碼時要記住的任何規則(我已經瀏覽過但沒有完全找到任何跨瀏覽器兼容性規則集)?
更新:
問題是在 IE 中,此模式窗口出現在屏幕大小的大約一半處。 在 FF 和 Chrome 中,模態窗口的大小與一美元硬幣差不多。
根據瀏覽器當前的渲染模式,您可能需要使用document.documentElement.scrollTop
而不是document.body.scrollTop
(對於scrollLeft
也是如此)。
Peter-Paul Koch 的一篇 Evolt 文章(在 quirksmode.org 中出名)中有關於這個問題的一些很好的背景,但它是從 2002 年開始的,現在有點過時了。
正如這里的其他人所建議的那樣,在 2011 年解決此類問題的最簡單方法就是使用現有的 JavaScript 框架。 jQuery非常流行(尤其是在 StackOverflow 用戶中),但還有很多其他的。
另一種解決方案:
(document.documentElement.scrollTop || document.body.scrollTop)
您可以使用:
window.pageYOffset
如果您認為不需要不必要的第三方庫,您可以嘗試:
var scrollTop = (document.documentElement || document.body.parentNode || document.body).scrollTop;
它是 hacky,但它仍然比 JQuery 好。
我遇到了同樣的問題,我檢查了我的代碼是否存在集合溢出,刪除:
overflow:auto;
從另一個元素工作
作為一種解決方法,我最終不得不每 x 毫秒檢查一次。 不理想,但它對我有用,因為我找不到任何其他解決方案。 請注意,這是 ES6 代碼,因此如果需要,您必須手動使其與 ES5 兼容,或者使用 Babel。
/**
* Set the scroll top on load
* @param {int} scrollTop The scrollTop
*/
let setScrollTop = scrollTop => {
// Different browsers treat this differently, so set all
window.scrollTop = scrollTop;
window.document.body.scrollTop = scrollTop;
window.document.documentElement.scrollTop = scrollTop;
};
/**
* Jump to a page
* @param {string} selector
*/
let jumpToPage = selector => {
let i = 0;
let top = document.querySelector(selector).offsetTop;
let interval;
interval = window.setInterval(() => {
if ((document.body.scrollTop || document.documentElement.scrollTop) === top || i === 20) {
window.clearInterval(interval);
return;
}
setScrollTop(top);
i++;
}, 100);
setScrollTop(top);
};
/**
* On load
*/
window.addEventListener('load', () => {
if (condition) {
jumpToPage(selector);
}
});
我會像 chrispanda 建議的那樣推薦 jQuery。 jQuery 有一個內置的滾動事件,其余的可以用幾行代碼來操作 html/css。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.