🚧elem.styleProp()
🔰 JS ⟩ DOM ⟩ Types ⟩ Element ⟩
⭐️ 注意: 從 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);
};
// ⭐️ 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'
function styleProp(elem, 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) elem.style[prop] = val;
else elem.style.setProperty(prop, val); // kebab case
}
// return prop
const style = getComputedStyle(elem);
return camelCase ? style[prop] : style.getPropertyValue(prop);
};
JS.info ⟩ Styles and classes
Window ⟩ .getComputedStyle() - returns an object (live
CSSStyleDeclaration
object) containing the values of all CSS properties of an element.CSSStyleDeclaration ⟩
.getPropertyValue() :
DOMString
| ''
.setProperty()
window.getComputedStyle(elem);
window.getComputedStyle(elem, pseudoElem);
// style get/set property
var value = style.getPropertyValue(prop);
style.setProperty(prop, value, priority);
CSS Properties - get/set CSS properties
codepen ⟩ elem.style
Last updated