萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 跨瀏覽器相容性處理:樣式、滾動、事件、Ajax 完整指南

1. 取得計算樣式

function getStyle(el, prop) {
    if (el.currentStyle) {           // IE 6-8
        return el.currentStyle[prop];
    }
    return getComputedStyle(el, null)[prop]; // 標準瀏覽器
}

// 使用
const width = getStyle(document.getElementById('box'), 'width');

現代寫法: window.getComputedStyle(el)[prop] 已全瀏覽器支援 (IE9+),舊專案維護才需相容寫法。

2. 捲軸位置

// 文檔捲動距離 (垂直)
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
// 水平
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
  • window.pageYOffset:現代標準 (IE9+)。
  • document.documentElement.scrollTop:標準模式下的文檔根元素。
  • document.body.scrollTop:Quirks 模式或舊版 WebKit。

3. 事件物件統一

function handleEvent(e) {
    e = e || window.event; // IE 使用全域 event
    const target = e.target || e.srcElement; // 事件源
    const key = e.keyCode || e.which;        // 鍵碼
    // 阻止預設
    if (e.preventDefault) e.preventDefault(); else e.returnValue = false;
    // 停止冒泡
    if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true;
}

4. 事件綁定/移除統一封裝

const EventUtil = {
    add(el, type, fn) {
        if (el.addEventListener) {
            el.addEventListener(type, fn, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + type, fn);
        } else {
            el['on' + type] = fn; // DOM0 級備援
        }
    },
    remove(el, type, fn) {
        if (el.removeEventListener) {
            el.removeEventListener(type, fn, false);
        } else if (el.detachEvent) {
            el.detachEvent('on' + type, fn);
        } else {
            el['on' + type] = null;
        }
    },
    getTarget(e) { return e.target || e.srcElement; },
    preventDefault(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; },
    stopPropagation(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; }
};

// 使用:注意 fn 必須為具名函式以便移除
function onClick(e) { console.log('clicked', EventUtil.getTarget(e)); }
EventUtil.add(document, 'click', onClick);
// 移除時
EventUtil.remove(document, 'click', onClick);

5. this 指向修正 (IE 附加事件 bug)

EventUtil.add(el, 'click', function(e) {
    e = e || window.event;
    const target = EventUtil.getTarget(e);
    // 在 attachEvent 中 this 指向 window,需用 target 或 call 修正
    console.log(this === window); // IE8 true
    // 修正:fn.call(el, e) 或使用 target
});

6. Ajax (XMLHttpRequest) 建立

function createXHR() {
    if (window.XMLHttpRequest) return new XMLHttpRequest(); // 標準
    // IE 5/6 ActiveXObject
    const versions = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'Microsoft.XMLHTTP'];
    for (const v of versions) {
        try { return new ActiveXObject(v); } catch (_) {}
    }
    throw new Error('XMLHttpRequest not supported');
}

// 現代:直接 new XMLHttpRequest() 或 fetch()
fetch('/api/data').then(r => r.json()).then(console.log);

7. 取消預設行為

 e.preventDefault()); // 現代
document.oncontextmenu = () => false; // 通用 (含舊 IE)

// 表單提交攔截
form.addEventListener('submit', e => {
    if (!validate()) e.preventDefault();
});

注意: addEventListener 中 return false **不會** 取消預設行為,必須用 e.preventDefault()。

8. call / apply / bind 差異

function greet(greeting, punct) { console.log(greeting + ', ' + this.name + punct); }
const obj = { name: 'Alice' };

greet.call(obj, 'Hello', '!');     // 參數列表
greet.apply(obj, ['Hi', '~']);     // 參數陣列
const bound = greet.bind(obj, 'Hey'); // 回傳新函式,預設參數
bound('?'); // Hey, Alice?
  • call/apply 立即執行;bind 回傳綁定後的新函式。
  • apply 適合參數數量不固定 (如 Math.max.apply(null, arr))。

9. 子節點取得:children vs childNodes

<div id="box">
  <span><a>Link</a></span>
  <span><a>Link</a></span>
</div>

const box = document.getElementById('box');
box.children.length;    // 2 (兩個 span,僅元素節點)
box.childNodes.length;  // 5 (現代瀏覽器含文字節點:換行、縮排)
box.children[0].children[0]; // 取得第一個 a
  • children:僅 **Element 節點**,IE9+ 全支援。
  • childNodes:所有節點 (元素、文字、註解),舊 IE 不計算文字節點導致長度差異。
  • **建議統一使用 children + firstElementChild / lastElementChild / nextElementSibling**。

總結:現代專案的相容策略

  1. **放棄 IE 8 以下**:專注 IE11+ / Edge / 現代瀏覽器,移除所有 hack。
  2. **使用 Polyfill**:Promise、fetch、Element.prototype.closest、Array.from 等透過 polyfill.io 或 core-js 引入。
  3. **建置工具轉譯**:Babel + @babel/preset-env 針對目標瀏覽器自動轉譯。
  4. **特性偵測優於瀏覽器偵測**:if ('fetch' in window) 而非 if (isIE)。

原生 JS 相容性知識是理解框架底層、除疑難雜症、面試必考的核心功力。現代開發雖多由框架屏蔽差異,但關鍵時刻仍需直搗底層解決問題。

copyright © 萬盛學電腦網 all rights reserved