返回博客

前端 JS 生成随机 CSS 样式

使用 JavaScript 生成随机的 CSS 样式,使页面元素在鼠标悬停时显示随机颜色。

Mt.r
|

期望每次打开页面鼠标悬停的时候,悬停颜色是随机的,而不是固定的。

const randomHoverColor = () => {
  // hsl(0deg 100% 96.5%);
  const h = Math.floor(Math.random() * 360);
  // const s = Math.floor(Math.random() * 100);
  // const l = Math.floor(Math.random() * 100);
  return `hsl(${h}deg 100% 99% / 85%)`;
};

const addRandomHoverColor = () => {
  const elements = document.documentElement;
  elements.style.setProperty("--hover-color", randomHoverColor());
};
 .button {
    background-color: var(--hover-color);
    &:hover {
      background-color: var(--hover-color);
    }
  }