// 示例代码:使用JavaScript设置CSS样式
// 方法1:通过元素的style属性直接设置样式
const element = document.getElementById('myElement');
element.style.color = 'red'; // 设置文本颜色为红色
element.style.fontSize = '20px'; // 设置字体大小为20像素
// 方法2:通过classList管理类名
const element2 = document.getElementById('myElement2');
element2.classList.add('active'); // 添加类名为'active'
element2.classList.remove('inactive'); // 移除类名为'inactive'
// 方法3:通过setAttribute设置整个style属性
const element3 = document.getElementById('myElement3');
element3.setAttribute('style', 'color: blue; font-size: 16px;'); // 设置多个样式
// 方法4:通过CSSStyleSheet对象添加样式规则(适用于全局样式)
const styleSheet = document.createElement('style');
styleSheet.type = 'text/css';
styleSheet.innerHTML = '.new-class { color: green; }';
document.head.appendChild(styleSheet); // 动态添加一个新的样式规则
style属性来设置内联样式。这种方式适合对单个元素进行样式修改。classList来管理类名,适合切换预定义的CSS类。这样可以避免重复的样式定义,并且更容易维护。setAttribute设置整个style属性,适合一次性设置多个样式。<style>标签并插入到<head>中,动态添加全局样式规则。这种方式适合需要在页面中动态添加或修改全局样式的场景。下一篇:js修改css样式
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站