css3 变量使用和修改变量

发布时间 2023-12-01 17:32:56作者: 男孩亮亮
<!DOCTYPE html>
<html>
<head>
<style>
:root {
  --blue: #1e90ff;
  --white: #ffffff; 
  --aa: 1212121;
}

body {
  background-color: var(--blue);
}

h2 {
  border-bottom: 2px solid var(--blue);
}

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

.container button  {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}
</style>

<script>
// 获取根元素
var r = document.querySelector(':root');

// 创建获取变量值的函数
function myFunction_get() {
  // 获取根的样式(属性和值)
  var rs = getComputedStyle(r);
  // 弹出 --blue 变量的值
  alert("The value of --aa is: " + rs.getPropertyValue('--aa'));
}

// 创建设置变量值的函数
function myFunction_set() {
  // 把变量 --blue 的值设置为另一个值(在这里是 "lightblue")
  r.style.setProperty('--blue', 'lightblue');
}
</script>
</head>
<body>

<h1>使用 JavaScript 获取和更改 CSS 变量</h1>

<div class="container">
  <h2>Welcome to Shanghai!</h2>
  <p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
  <p>Shanghai is one of the four direct-administered municipalities of the People's Republic of China.</p>
  <p>
    <button>Yes</button>
    <button>No</button>
  </p>
</div>
<br>

<button type="button" onclick="myFunction_get()">使用 JavaScript 来获取 CSS 变量</button>
<button type="button" onclick="myFunction_set()">使用 JavaScript 来更改 CSS 变量</button>

</body>
</html>