通过单击操作 CSS-变量

Manipulate a CSS-Variable by clicking

我想在每次点击时将元素 属性 的值加倍。因此,我正在使用 CSS-变量。 所以我正在尝试这样做:

#circle_1 {
width:50px;
height:50px;
width: var(--size_1, 50px);
height: var(--size_1, 50px);
}

还有那个:

// Vars
var circle_1 = document.querySelector("#circle_1");
var size_1 = document.getPropertyValue("--size_1");

// Function to grow the circle
function growCircle() {
var size_1_n =size_1*2;
  circle_1.style.setProperty("--size_1", size_1_n.value);
}

// Event listener
var el = document.getElementById("circle_1");
el.addEventListener("click", growCircle, false);

你可以在这里看到它https://codepen.io/daiaiai/pen/QQXrGz

什么都没发生。我认为(至少) var size_1 = document.getPropertyValue("--size_1"); 有问题 但我真的想不通。你能指导我一点(很多)吗?

你的代码笔有很多问题,所以我会清理你的代码,并提供一个工作示例。

以下是一些关键变化:

  1. 我为变量添加了一个 :root 声明。这允许我在元素 circle_1 处获取 --size_1 的值。没有这个,你会得到 NaN 作为变量的值,因为它没有在样式中的任何地方声明。

    可以 编写一些条件来获得计算的 widthheight 值,但我觉得将默认值放在 :root.

  2. 由于您设置的值类似于 50px 而不是 50,即带有单位的值,因此您需要在将其加倍之前从中取出数字部分.我为此使用 parseInt(size_1)

var circle_1 = document.querySelector("#circle_1");
var size_1 = document.body.style.getPropertyValue("--size_1");

// Function to grow the circle
function growCircle() {
  var size_1 = window.getComputedStyle(circle_1).getPropertyValue("--size_1");
  var size_1_n = parseInt(size_1) * 2;
  circle_1.style.setProperty("--size_1", size_1_n + "px");
}


// Event listener
circle_1.addEventListener("click", growCircle, false);
:root {
  --size_1: 50px;
}

body {
  margin: 100px;
}

#circle_1 {
  width: var(--size_1, 50px);
  height: var(--size_1, 50px);
  border-radius: 50%;
  margin-top: 20px;
  background-color: pink;
  opacity: 0.7;
  display: inline-block;
  transition: 0.3s;
}

div span {
  position: relative;
  top: 50%;
  left: 50%;
  text-align: center;
}
<div id="circle_1" draggable="true"><span>Group 1<span></div>


对此稍有不同的方法是仅在变量的 :root 声明中声明值部分。然后您可以使用 width: calc(var(--size_1) * 1px).

引用它的值

我个人更喜欢这种方法,因为变量只携带值部分,并且您可以在声明样式时应用任何您喜欢的单位。此外,这将允许您避免变量值的 parseInt

这是采用该方法的片段:

var circle_1 = document.querySelector("#circle_1");
var size_1 = document.body.style.getPropertyValue("--size_1");

// Function to grow the circle
function growCircle() {
  var size_1 = window.getComputedStyle(circle_1).getPropertyValue("--size_1");
  var size_1_n = size_1 * 2;
  circle_1.style.setProperty("--size_1", size_1_n);
}


// Event listener
circle_1.addEventListener("click", growCircle, false);
:root {
  --size_1: 50;
}

body {
  margin: 100px;
}

#circle_1 {
  width: calc(var(--size_1, 50px) * 1px);
  height: calc(var(--size_1, 50px) * 1px);
  border-radius: 50%;
  margin-top: 20px;
  background-color: pink;
  opacity: 0.7;
  display: inline-block;
  transition: 0.3s;
}

div span {
  position: relative;
  top: 50%;
  left: 50%;
  text-align: center;
}
<div id="circle_1" draggable="true"><span>Group 1<span></div>