You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript修改CSS属性?HTML按钮切换圆圈颜色实现

嘿,我来帮你搞定这两个问题!先从基础的JavaScript修改CSS属性的方法说起,再给你写好具体的实战代码。

如何使用JavaScript修改CSS属性?

日常开发里,常用的方法主要有三种,各有适用场景:

  • 直接修改元素的style属性
    这是最直观的方式,适合快速修改单个CSS属性。注意这里的CSS属性名要改成驼峰式(比如background-color要写成backgroundColor),示例代码:
// 获取目标元素
const targetElement = document.getElementById('myElement');
// 修改背景色
targetElement.style.backgroundColor = 'crimson';
// 修改字体大小
targetElement.style.fontSize = '20px';
  • 通过操作CSS类名批量修改样式
    如果需要一次性修改多个样式,或者想复用预设的样式规则,这种方式更优雅。先在CSS里定义好类,再用JS添加/移除类:
/* 提前在样式表中定义类 */
.active-card {
  background-color: #f0f9ff;
  border: 2px solid #3b82f6;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
const card = document.getElementById('userCard');
// 添加类
card.classList.add('active-card');
// 移除类
card.classList.remove('active-card');
// 切换类(存在就移除,不存在就添加)
card.classList.toggle('active-card');
  • 使用CSS变量(自定义属性)统一修改
    如果需要同时修改多个元素的样式,CSS变量会非常高效。先在CSS里定义变量,再用JS修改变量值:
/* 在根元素定义全局变量 */
:root {
  --primary-color: #22c55e;
}
/* 多个元素使用这个变量 */
.btn { background-color: var(--primary-color); }
.alert { border-left: 4px solid var(--primary-color); }
// 修改根元素的CSS变量
document.documentElement.style.setProperty('--primary-color', '#ef4444');
实战案例:点击按钮更改绿色圆圈的颜色

针对你的需求,我已经写好了index.html和change.js的完整代码,直接复制就能用:

index.html 文件内容

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>更改圆圈颜色</title>
  <style>
    .circle {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      background-color: green;
      margin: 30px 0;
      transition: background-color 0.3s ease; /* 加个过渡动画更丝滑 */
    }
    #changeColorBtn {
      padding: 12px 24px;
      font-size: 16px;
      border: none;
      border-radius: 6px;
      background-color: #3b82f6;
      color: white;
      cursor: pointer;
      transition: background-color 0.2s;
    }
    #changeColorBtn:hover {
      background-color: #2563eb;
    }
  </style>
</head>
<body>
  <!-- 绿色圆圈元素 -->
  <div class="circle" id="colorCircle"></div>
  <!-- 触发修改的按钮 -->
  <button id="changeColorBtn">点击更改圆圈颜色</button>

  <!-- 引入脚本文件 -->
  <script src="change.js"></script>
</body>
</html>

change.js 文件内容

// 获取按钮和圆圈元素
const changeBtn = document.getElementById('changeColorBtn');
const colorCircle = document.getElementById('colorCircle');

// 给按钮绑定点击事件
changeBtn.addEventListener('click', () => {
  // 方案1:固定修改为某一种颜色(比如蓝色)
  // colorCircle.style.backgroundColor = 'blue';

  // 方案2:随机生成颜色(更有趣)
  const randomHexColor = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
  colorCircle.style.backgroundColor = randomHexColor;
});

我还给样式加了点过渡动画,让颜色变化更丝滑~你可以根据需求选择固定颜色或者随机颜色的方案。

内容的提问来源于stack exchange,提问作者maestro777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:41:23