实现将 JS 变量绑定到 CSS 变量上,可以通过以下步骤实现:

  1. 在 CSS 中定义一个变量,例如:
:root {
  --color: #000;
}
  1. 在 JS 中获取需要绑定的元素,并设置其样式的变量值,例如:
const element = document.querySelector('.my-element');
element.style.setProperty('--color', '#f00');
  1. 当需要改变变量值时,只需要修改 JS 中的变量值即可,例如:
const newColor = '#0f0';
element.style.setProperty('--color', newColor);

这样就实现了将 JS 变量绑定到 CSS 变量上,可以实现动态修改样式的效果。


原文地址: https://www.cveoy.top/t/topic/boTJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录