Skip to content

DOM CSS

DOM CSS 的概念

DOM CSS 是指使用 DOM API 操作 HTML 元素的样式。通过 DOM CSS,我们可以动态修改元素的样式属性,实现各种视觉效果和动画。

访问和修改样式

1. style 属性

每个 HTML 元素都有一个 style 属性,它是一个对象,包含了元素的内联样式:

javascript
const element = document.getElementById("myElement");

// 获取样式属性
console.log(element.style.color);
console.log(element.style.fontSize);

// 设置样式属性
element.style.color = "red";
element.style.fontSize = "20px";
element.style.backgroundColor = "yellow";

注意:样式属性名使用驼峰命名法(如 fontSize 而不是 font-size)。

2. 获取计算样式

window.getComputedStyle() 方法用于获取元素的计算样式(包括内联样式、内部样式和外部样式):

javascript
const element = document.getElementById("myElement");
const computedStyle = window.getComputedStyle(element);

// 获取计算样式
console.log(computedStyle.color);
console.log(computedStyle.fontSize);
console.log(computedStyle.backgroundColor);

注意:计算样式是只读的,不能直接修改。

3. 类操作

使用 classList 属性可以方便地管理元素的类:

add()

添加一个或多个类:

javascript
const element = document.getElementById("myElement");
element.classList.add("class1", "class2");

remove()

移除一个或多个类:

javascript
const element = document.getElementById("myElement");
element.classList.remove("class1", "class2");

toggle()

切换类的存在状态:

javascript
const element = document.getElementById("myElement");
element.classList.toggle("active"); // 如果存在则移除,不存在则添加

// 第二个参数可以强制添加或移除
element.classList.toggle("active", true); // 强制添加
element.classList.toggle("active", false); // 强制移除

contains()

检查元素是否包含某个类:

javascript
const element = document.getElementById("myElement");
console.log(element.classList.contains("active")); // 输出: true 或 false

replace()

替换一个类为另一个类:

javascript
const element = document.getElementById("myElement");
element.classList.replace("oldClass", "newClass");

样式操作的示例

1. 动态修改样式

javascript
const element = document.getElementById("myElement");

// 修改文本颜色
element.style.color = "blue";

// 修改字体大小
element.style.fontSize = "24px";

// 修改背景颜色
element.style.backgroundColor = "#f0f0f0";

// 修改边框
element.style.border = "1px solid black";

// 修改内边距
element.style.padding = "10px";

// 修改外边距
element.style.margin = "5px";

2. 切换样式类

javascript
const button = document.getElementById("toggleButton");
const element = document.getElementById("myElement");

button.addEventListener("click", function () {
  element.classList.toggle("highlight");
});

CSS:

css
.highlight {
  background-color: yellow;
  font-weight: bold;
  padding: 10px;
}

3. 动画效果

javascript
const element = document.getElementById("animateElement");
let position = 0;

function animate() {
  position += 1;
  element.style.left = position + "px";

  if (position < 300) {
    requestAnimationFrame(animate);
  }
}

// 开始动画
animate();

CSS:

css
#animateElement {
  position: relative;
  width: 100px;
  height: 100px;
  background-color: red;
}

4. 响应式设计

javascript
function checkScreenSize() {
  const element = document.getElementById("myElement");

  if (window.innerWidth < 768) {
    element.classList.add("mobile");
    element.classList.remove("desktop");
  } else {
    element.classList.add("desktop");
    element.classList.remove("mobile");
  }
}

// 初始检查
checkScreenSize();

// 监听窗口大小变化
window.addEventListener("resize", checkScreenSize);

CSS:

css
.desktop {
  font-size: 16px;
  padding: 20px;
}

.mobile {
  font-size: 14px;
  padding: 10px;
}

样式操作的最佳实践

1. 使用类而不是内联样式

优先使用类来管理样式,而不是直接修改内联样式:

javascript
// 好的做法:使用类
const element = document.getElementById("myElement");
element.classList.add("highlight");

// 不好的做法:直接修改内联样式
const element = document.getElementById("myElement");
element.style.backgroundColor = "yellow";
element.style.fontWeight = "bold";
element.style.padding = "10px";

CSS:

css
.highlight {
  background-color: yellow;
  font-weight: bold;
  padding: 10px;
}

2. 批量修改样式

对于多个样式属性的修改,使用类或 CSS 变量:

javascript
// 好的做法:使用类
const element = document.getElementById("myElement");
element.classList.add("theme-dark");

// 不好的做法:逐个修改样式属性
const element = document.getElementById("myElement");
element.style.backgroundColor = "#333";
element.style.color = "#fff";
element.style.borderColor = "#555";

CSS:

css
.theme-dark {
  background-color: #333;
  color: #fff;
  border-color: #555;
}

3. 使用 CSS 变量

CSS 变量(也称为自定义属性)可以方便地管理样式:

javascript
// 设置 CSS 变量
document.documentElement.style.setProperty("--primary-color", "blue");
document.documentElement.style.setProperty("--font-size", "16px");

// 获取 CSS 变量
const primaryColor = getComputedStyle(
  document.documentElement
).getPropertyValue("--primary-color");
console.log(primaryColor); // 输出: blue

CSS:

css
:root {
  --primary-color: red;
  --font-size: 14px;
}

.element {
  color: var(--primary-color);
  font-size: var(--font-size);
}

4. 避免频繁的样式计算

频繁的样式计算会影响性能,应该尽量避免:

javascript
// 好的做法:缓存样式值
const element = document.getElementById("myElement");
const computedStyle = window.getComputedStyle(element);
const originalColor = computedStyle.color;
const originalFontSize = computedStyle.fontSize;

// 不好的做法:频繁计算样式
const element = document.getElementById("myElement");
for (let i = 0; i < 100; i++) {
  const color = window.getComputedStyle(element).color;
  console.log(color);
}

5. 使用 requestAnimationFrame

对于动画效果,使用 requestAnimationFrame 可以提高性能:

javascript
// 好的做法:使用 requestAnimationFrame
const element = document.getElementById("animateElement");
let position = 0;

function animate() {
  position += 1;
  element.style.left = position + "px";

  if (position < 300) {
    requestAnimationFrame(animate);
  }
}

// 开始动画
animate();

// 不好的做法:使用 setTimeout
const element = document.getElementById("animateElement");
let position = 0;

function animate() {
  position += 1;
  element.style.left = position + "px";

  if (position < 300) {
    setTimeout(animate, 16); // 约 60fps
  }
}

// 开始动画
animate();

样式操作的常见错误

1. 样式属性名错误

忘记使用驼峰命名法:

javascript
const element = document.getElementById("myElement");

// 错误:使用连字符
// element.style.font-size = '20px';

// 正确:使用驼峰命名法
element.style.fontSize = "20px";

2. 忘记单位

设置尺寸类样式时忘记添加单位:

javascript
const element = document.getElementById("myElement");

// 错误:忘记单位
// element.style.width = '100';

// 正确:添加单位
element.style.width = "100px";
element.style.width = "50%";

3. 直接修改计算样式

尝试修改计算样式:

javascript
const element = document.getElementById("myElement");
const computedStyle = window.getComputedStyle(element);

// 错误:计算样式是只读的
// computedStyle.color = 'red';

// 正确:修改内联样式或类
element.style.color = "red";
element.classList.add("red-text");

4. 过度使用内联样式

过度使用内联样式会使代码难以维护:

javascript
// 不好的做法:过度使用内联样式
const element = document.getElementById("myElement");
element.style.color = "red";
element.style.fontSize = "20px";
element.style.backgroundColor = "yellow";
element.style.padding = "10px";
element.style.margin = "5px";
element.style.border = "1px solid black";

// 好的做法:使用类
const element = document.getElementById("myElement");
element.classList.add("highlight");

5. 频繁操作 DOM 样式

频繁修改 DOM 样式会导致重排和重绘,影响性能:

javascript
// 不好的做法:频繁修改样式
const element = document.getElementById("myElement");
for (let i = 0; i < 100; i++) {
  element.style.left = i + "px";
}

// 好的做法:使用 transform
const element = document.getElementById("myElement");
element.style.transform = "translateX(100px)";

小结

DOM CSS 是使用 DOM API 操作 HTML 元素样式的技术,它允许我们动态修改元素的样式属性,实现各种视觉效果和动画。通过本文介绍的方法,你可以有效地操作元素的样式,创建美观、交互式的网页应用。在实际开发中,应该遵循最佳实践,提高代码性能和可维护性。