關於scrollLeft,scrollTop的瀏覽器安全色性測試

來源:互聯網
上載者:User

今天在修改原群組彈窗的時候,發現彈窗在Google瀏覽器chrome下的位置跟在別的瀏覽器下不一樣.逐一排查,肯定是在計算視窗位置的時候,少加了scrollTop這個值.在查看原始碼的時候發現直接採用

document.documentElement.scrollTop這個,但在chrome下這個值為0.

在有文檔聲明的情況下,也就是第一行有個dtd聲明,標準瀏覽器認識document.documentElement.scrollTop,可chrome竟然不認識這斯.在沒有文檔聲明的情況下,chrome,safari還是可以讀取到scrollTop值.因為chrome是通過document.body.scrollTop擷取值的.

解決這個問題:不用去那麼麻煩去判斷瀏覽器類別,因為在不同情況下,document.body、document.documentElement都有可能擷取到不同的值的特點.問題就很好解決.
在擷取瀏覽器或某div的scrollTop或scrollLeft時,我封裝了一個方法:
複製代碼 代碼如下:
var ueScroll=(function(){
//擷取scrollX
function scrollX(ele){
var element=ele || document.body;
return element.scrollLeft || (document.documentElement && document.documentElement.scrollLeft);
}
//擷取scrollY
function scrollY(ele){
var element=ele || document.body;
return element.scrollTop || (document.documentElement && document.documentElement.scrollTop);
}
return {
left:scrollX,
top:scrollY
}
})()

在DEMO中各瀏覽器擷取scrollTop,scrollLeft值差異性調用的方式也很方便簡單的,只要跟普通的對象調用方式一樣.

這個也可以直接用在textarea或div擷取scrollTop,scrollLeft上的,只要後面傳進一個dom對象即可.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.