[note] CSS Manipulation with JavaScript
keywords: DOM
, element
, CSS
, style
- Element API @ MDN Web APIs - Document Object Model
- [示範]程式碼與畫面
CSS Class
使用 classList 添加移除 class
keywords: element.classList
// 透過 classList 除了可以增減 class 之外,還可以取得 class 數目和名稱
el.classList.add('className', 'className2'); // 新增多個 class
el.classList.remove('className');
el.classList.item(Number);
el.classList.toggle('className');
el.classList.contains('className');
使用 className 修改某一元素套用的 class
keywords: element.className
透過 className
這個屬性,可以直接設定(set)或取得(get)某一元素的 css class
:
const element = document.getElementById('item');
element.className = 'inactive';
Inline style
keywords: getPropertyValue(<property>)
, setProperty(<property>, <value>)
, removeProperty(<property>)
// 針對行內樣式(inline-style)
element.style.setProperty('--primary-btn-text-color', 'darkcyan'); // 設值
element.style.getPropertyValue('--primary-btn-text-color'); // 取值
element.style.removeProperty('--primary-btn-text-color'); // 移除值
取得元素 computed 後的樣式值
// 取得 computed 後的樣式
// getComputedStyle(element[, pseudoElt]).getPropertyValue('background-color')
getComputedStyle(<element>).getPropertyValue('--primary-btn-bg-color');
/*
fontSize=window.getComputedStyle(div,'::before').getPropertyValue('font-size');
*/
CSS 變數的操作(CSS custom properties / variables)
// 取值
HTMLelement.style.getProperty('--primary-btn-bg-color'); // inline-style
getComputedStyle('html-element').getPropertyValue('--primary-btn-bg-color'); // 取得 computed 後的結果
// 設值
HTMLElement.style.setProperty('<cssVariable>', '<value>');
HTMLElement.style.setProperty('--btn-primary-color', 'darkcyan');
// 移除
HTMLElement.style.removeProperty('--primary-btn-bg-color', 'red');
參考
- 利用 javascript 獲取並修改偽元素的值 @ segmentfault
- Node.textContent @ MDN
- Element in Web API @ MDN
- HTMLElement in Web API @ MDN