在 JavaScript 中,我们可以通过 DOM 操作来修改元素的样式和类,从而实现动态的页面效果。以下是主要的操作方法:
获取或设置元素的 class 属性(字符串形式):
element.className = "new-class"; // 替换所有类
更现代的类操作方法,返回一个 DOMTokenList 对象:
// 添加类
element.classList.add('new-class');
// 移除类
element.classList.remove('old-class');
// 切换类(有则移除,无则添加)
element.classList.toggle('active');
// 检查是否包含某个类
if (element.classList.contains('hidden')) {
// 元素有 hidden 类
}
// 替换类
element.classList.replace('old-class', 'new-class');
直接修改元素的内联样式:
// 设置单个样式
element.style.color = 'blue';
element.style.backgroundColor = '#f0f0f0';
element.style.fontSize = '16px';
// 注意:CSS 属性名使用驼峰命名法
element.style.marginTop = '10px';
// 使用 cssText 批量设置
element.style.cssText = 'color: red; background: black; width: 100px';
// 或者使用 setAttribute
element.setAttribute('style', 'color: red; background: black');
获取元素最终应用的所有样式(包括样式表中的样式):
const computedStyle = window.getComputedStyle(element);
const width = computedStyle.width;
const color = computedStyle.color;
优先使用类操作:通过添加/移除类来改变样式,而不是直接修改 style 属性
使用 classList 而不是 className:
动画性能优化:
// 切换主题
function toggleTheme() {
const body = document.body;
body.classList.toggle('dark-theme');
// 或者直接修改样式(不推荐)
// body.style.backgroundColor = body.style.backgroundColor === 'black' ? 'white' : 'black';
}
// 显示/隐藏元素
function toggleElement(id) {
const el = document.getElementById(id);
el.classList.toggle('hidden');
// 或者直接修改样式
// el.style.display = el.style.display === 'none' ? 'block' : 'none';
}
通过合理使用这些方法,你可以创建动态、交互性强的网页界面。
热门推荐:
0