1. 程式人生 > >用JavaScript更新CSS變數

用JavaScript更新CSS變數

HTML

<div class="mover"></div>

CSS

.mover {
  width: 50px;
  height: 50px;
  background: red;
  position: absolute;
  left: var(--mouse-x);
  top: var(--mouse-y);
}

JS

let root = document.documentElement;

root.addEventListener("mousemove", e => {
  root.style.setProperty(
'--mouse-x', e.clientX + "px"); root.style.setProperty('--mouse-y', e.clientY + "px"); });