🚧elem.styleProp()

🔰 JSDOMTypesElement

⭐️ 注意: 從 getComputedStyle(elem) 得到的 style 是唯讀的 (read-only),不可設定新值給它,否則會產生以下錯誤❗️

🧨 NoModificationAllowedError: Failed to set the 'padding-left' property on 'CSSStyleDeclaration': These styles are computed, and therefore the 'padding-left' property is read-only.

// ⭐️ elem.styleProp(prop[,val])
//    get: 
//         elem.styleProp('padding-left') 
//       = elem.styleProp('paddingLeft')
//       = getComputedStyle(elem).paddingLeft
//       ≠ elem.style.paddingLeft ❗️
//    set: 
//         elem.styleProp('padding-left', '8px') 
//       = elem.styleProp('paddingLeft', '8px')
//       = elem.style.paddingLeft = '8px'
Element.prototype.styleProp = function(prop, val=undefined){
  
    const camelCase = !prop.includes('-');
  
    // set prop if necessary
    // ⭐️ Note: 
    //    getComputedStyle() is read-only, DO NOT use it to set new value,
    //    use `this.style` instead❗️
    if (val) {
      if (camelCase) this.style[prop] = val;
      else this.style.setProperty(prop, val);  // kebab case
    }
  
    // return prop  
    const style = getComputedStyle(this);
    return camelCase ? style[prop] : style.getPropertyValue(prop);    
};

Last updated