// 通过 JavaScript 添加样式
// 示例 1: 直接修改元素的 style 属性
const element = document.getElementById('myElement');
element.style.color = 'blue'; // 修改文本颜色为蓝色
element.style.fontSize = '20px'; // 修改字体大小为 20px
// 示例 2: 添加或移除 CSS 类
const element2 = document.getElementById('myElement2');
element2.classList.add('new-class'); // 添加一个名为 'new-class' 的类
element2.classList.remove('old-class'); // 移除一个名为 'old-class' 的类
// 示例 3: 使用 setAttribute 方法添加内联样式
const element3 = document.getElementById('myElement3');
element3.setAttribute('style', 'background-color: yellow; padding: 10px;');
// 示例 4: 动态创建 <style> 标签并添加 CSS 规则
const styleSheet = document.createElement('style');
styleSheet.type = 'text/css';
styleSheet.innerHTML = '.highlight { background-color: green; color: white; }';
document.head.appendChild(styleSheet);
style 属性:通过 element.style.property 可以直接设置内联样式的属性。classList.add() 和 classList.remove() 可以动态地管理元素的 CSS 类。setAttribute 添加内联样式:可以通过 setAttribute('style', ...) 来一次性设置多个样式属性。<style> 标签:可以创建一个新的 <style> 标签并将自定义的 CSS 规则插入到页面中。上一篇:js 添加css
下一篇:js display
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站