ZetCode

JavaScript element.style.property

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 element.style.property。此属性允许直接操作元素的内联样式,从而提供对外观和布局的动态控制。

基本定义

element.style 属性返回一个 CSSStyleDeclaration 对象,该对象代表元素的 style 属性。它提供了对该元素所有内联 CSS 属性的访问。

属性的访问和修改使用 CSS 属性名称的驼峰式命名法。例如,background-color 在 JavaScript 中变为 backgroundColor

通过 element.style 所做的更改直接应用于元素的内联 style 属性,从而覆盖外部 CSS 文件或 <style> 标签中的任何样式。

更改背景颜色

本示例演示如何使用 element.style.backgroundColor 更改元素的背景颜色。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Background Color Change</title>
</head>
<body>

<div id="colorBox" style="width: 200px; height: 200px; border: 1px solid black;">
    Click to change color
</div>

<script>
    const box = document.getElementById('colorBox');
    box.addEventListener('click', function() {
        this.style.backgroundColor = '#' + Math.floor(Math.random()*16777215).toString(16);
    });
</script>

</body>
</html>

在此示例中,我们有一个 div 元素,点击时会更改其背景颜色。颜色使用十六进制表示法随机生成。

每次单击元素时,都会将 style.backgroundColor 属性设置为新值。请注意 JavaScript 中的 CSS 属性名称是如何采用驼峰式命名的。

为元素位置添加动画

本示例展示了如何使用 element.style 属性为元素位置添加动画。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Position Animation</title>
    <style>
        #movingBox {
            width: 50px;
            height: 50px;
            background-color: red;
            position: absolute;
        }
    </style>
</head>
<body>

<div id="movingBox"></div>
<button id="animateBtn">Start Animation</button>

<script>
    const box = document.getElementById('movingBox');
    const btn = document.getElementById('animateBtn');
    let pos = 0;
    let animationId;

    btn.addEventListener('click', function() {
        if (animationId) {
            cancelAnimationFrame(animationId);
            animationId = null;
            btn.textContent = 'Start Animation';
            return;
        }
        
        btn.textContent = 'Stop Animation';
        animate();
    });

    function animate() {
        pos = (pos + 2) % 400;
        box.style.left = pos + 'px';
        box.style.top = pos + 'px';
        animationId = requestAnimationFrame(animate);
    }
</script>

</body>
</html>

此示例创建一个简单的动画,其中一个框在屏幕上对角线移动。使用 style.leftstyle.top 属性更新位置。

动画使用 requestAnimationFrame 以获得流畅的性能。请注意,在设置位置值时必须包含单位 (px)。

切换可见性

本示例演示如何使用 element.style.display 切换元素的可见性。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Toggle Visibility</title>
</head>
<body>

<button id="toggleBtn">Toggle Content</button>
<div id="content" style="padding: 20px; background-color: #f0f0f0; margin-top: 10px;">
    This content can be shown or hidden.
</div>

<script>
    const btn = document.getElementById('toggleBtn');
    const content = document.getElementById('content');
    
    btn.addEventListener('click', function() {
        if (content.style.display === 'none') {
            content.style.display = 'block';
        } else {
            content.style.display = 'none';
        }
    });
</script>

</body>
</html>

在此示例中,单击按钮可以通过在 'none' 和 'block' 之间切换其 display 样式属性来切换内容 div 的可见性。

这是显示/隐藏元素的常见模式。初始状态由检查 style.display 的当前值确定。

动态字体样式

本示例展示了如何使用 element.style 动态更改字体属性。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Font Styling</title>
</head>
<body>

<div id="text" style="padding: 20px;">
    This text will change based on your selections.
</div>

<select id="fontFamily">
    <option value="Arial">Arial</option>
    <option value="Times New Roman">Times New Roman</option>
    <option value="Courier New">Courier New</option>
</select>

<input type="range" id="fontSize" min="10" max="40" value="16">

<script>
    const text = document.getElementById('text');
    const fontFamily = document.getElementById('fontFamily');
    const fontSize = document.getElementById('fontSize');
    
    fontFamily.addEventListener('change', function() {
        text.style.fontFamily = this.value;
    });
    
    fontSize.addEventListener('input', function() {
        text.style.fontSize = this.value + 'px';
    });
</script>

</body>
</html>

此示例允许用户使用表单控件更改文本的字体系列和大小。更改通过 style.fontFamilystyle.fontSize 立即应用。

请注意,字体大小需要单位 (px),而字体系列可以直接接受字符串值。事件监听器实时响应用户输入。

复杂的样式转换

本示例演示了使用 element.style.transform 进行复杂的样式转换。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Transformations</title>
    <style>
        #transformBox {
            width: 100px;
            height: 100px;
            background-color: #4CAF50;
            margin: 50px auto;
            transition: transform 0.5s ease;
        }
    </style>
</head>
<body>

<div id="transformBox"></div>
<button id="rotateBtn">Rotate</button>
<button id="scaleBtn">Scale</button>
<button id="resetBtn">Reset</button>

<script>
    const box = document.getElementById('transformBox');
    const rotateBtn = document.getElementById('rotateBtn');
    const scaleBtn = document.getElementById('scaleBtn');
    const resetBtn = document.getElementById('resetBtn');
    
    rotateBtn.addEventListener('click', function() {
        box.style.transform = 'rotate(45deg)';
    });
    
    scaleBtn.addEventListener('click', function() {
        box.style.transform = 'scale(1.5)';
    });
    
    resetBtn.addEventListener('click', function() {
        box.style.transform = 'none';
    });
</script>

</body>
</html>

此示例展示了如何通过 JavaScript 应用 CSS 转换。可以使用按钮旋转、缩放或将框重置为原始状态。

CSS 中的 transition 属性确保状态之间的平滑动画。可以将多个转换组合在单个字符串中以获得更复杂的效果。

来源

MDN HTMLElement.style 文档

在本文中,我们探讨了 JavaScript 中的 element.style.property。此强大功能可实现网页的动态样式设置,从而实现交互式和响应式用户界面。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 JS DOM 教程