前言
JavaScript 的坑不少,而瀏覽器之間的差異肯定是其中最經典的一類。本文把日常開發裡最常碰到的幾個相容性寫法整理成一份速查表,方便日後翻閱參考。如果你有更好的做法,歡迎留言交流。
在 IE9+、Chrome、Firefox、Opera 與 Safari 這些現代瀏覽器中,直接用 window.innerWidth 拿寬度、window.innerHeight 拿高度即可:
var msg = "窗口寬度:" + window.innerHeight + "\n窗口高度:" + window.innerWidth; alert(msg );
如果是 IE5/6/7/8(Chrome 與 Firefox 其實也支援),則要改用 document.documentElement 的 clientWidth 與 clientHeight:
var msg = "窗口寬度:" + document.documentElement.clientWidth + "\n窗口高度:" + document.documentElement.clientHeight; alert(msg);
實務上最省事的寫法,就是把上面兩種寫法用「或」串起來,一行即可覆蓋幾乎所有瀏覽器:
var w = window.innerWidth || document.documentElement.clientWidth; var h = window.innerHeight || document.documentElement.clientHeight; alert("窗口寬度:" + w + "\n窗口高度:" + h);
IE 系列要走 物件.currentStyle["屬性名"];其他瀏覽器則是 window.getComputedStyle(物件, null)["屬性名"]。
這裡有個容易踩的雷:內部樣式表與外部樣式表的屬性只能讀、不能改。真要修改,得透過行間樣式(inline style)下手,因為行間樣式的優先權最高,會直接蓋掉前兩者。
為了少寫 if-else,實務上一般都會包成一個 getStyle 方法:
<body> <div id="box1"></div> <script type="text/javascript"> var box1 = document.getElementById("box1"); // alert(box1.currentStyle["width"]); //只支援 IE // alert(window.getComputedStyle(box1, null)["height"]); //支援 IE 以外的瀏覽器 alert(getStyle(box1, "backgroundColor")); /* 為了簡化書寫並相容各瀏覽器,通常會封裝成一個方法 */ function getStyle (obj, attributeName) { if(obj.currentStyle){ //存在 currentStyle 即代表處於 IE 環境 return obj.currentStyle[attributeName]; }else { //其他瀏覽器 return window.getComputedStyle(obj, null)[attributeName]; } } </script> </body>
監聽捲動時,跨瀏覽器取得捲動距離可以用位元或串接兩種來源:
<script type="text/javascript"> window.onscroll = function () { console.log("開始滾動..."); //跨瀏覽器取得捲動距離 console.log(document.documentElement.scrollTop | document.body.scrollTop); } </script>
IE 早期版本不會主動把 event 傳進事件處理函式,得從 window.event 撈,因此常見寫法是先用 || 做一次兜底:
box.onclick = function(event) { event = event || window.event; console.log("offsetX:" + event.offsetX + " offsetY:" + event.offsetY); console.log("screenX:" + event.screenX + " screenY:" + event.screenY); console.log("clientX:" + event.clientX + " clientY:" + event.clientY); console.log("pageX:" + event.pageX + " pageY: " + event.pageY); }
以上就是這份相容性寫法整理的全部內容。老實說,隨著現代瀏覽器越來越統一標準,這些判斷式多半只在你需要維護老專案時才用得上,但懂了至少心裡踏實。