首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript style.setAttribute 兼容性問題與標準替代方案

     編輯:程式設計綜合問答

問題

obj.style.setAttribute(name, value) 在 Chrome/Firefox 中**不支持**(CSSStyleDeclaration 無此方法),IE 早期版本支持但非標準。

標準替代方案

**直接用括號/點語法設置 style 屬性**:

// 設置單個樣式
element.style[propertyName] = value;        // 動態屬性名
element.style.propertyName = value;         // 靜態屬性名(駝峰)
// 例
element.style['background-color'] = 'red';  // 支持連字符
element.style.backgroundColor = 'red';      // 推薦駝峰

批量設置/獲取

  • element.style.cssText = 'color:red; font-size:14px;' 一次性設置多條,會覆蓋原有內聯樣式。
  • window.getComputedStyle(element).propertyName 獲取**最終計算樣式**(含 CSS 類、繼承)。

修正原代碼

function setCellStyle(name, value, isStyleAttribute) {
    try {
        if (isStyleAttribute) {
            o._currentCell.style[name] = value;  // 直接賦值
            var o_span = getSpan(o._currentCell);
            if (o_span) {
                o_span.style[name] = value;
            }
        }
    } catch (ex) {
        console.error(ex); // 現代調試用 console.error
    }
}

總結

棄用 style.setAttribute,改用 style[prop] = val 或 style.cssText**。這是 W3C DOM Level 2 Style 標準,全瀏覽器兼容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved