css button的hover效果覆盖过渡

107 阅读2分钟

按钮的hover效果覆盖过渡,先看看最终效果

hoverButton.gif

代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Hover mouse</title>
  </head>
  <style>
    @property --r {
      syntax: "<length-percentage>";
      initial-value: 0;
      inherits: false;
    }
    html,
    body {
      display: grid;
    }
    html {
      height: 100%;
    }
    button {
      place-self: center;
      border: 2px solid white;
      padding: 0 1em;
      border-radius: 2em;
      background: radial-gradient(
          circle at var(--x, 0%) var(--y, 0%),
          #fffce1 calc(var(--r) - 1px),
          orange var(--r)
        )
        border-box;
      color: white;
      font: 1.5em/2.25 ubuntu;
      transition: --r 0.35s;
    }
    button:hover {
      --r: 100%;
      color: black;
    }
  </style>
  <body>
    <button>Button</button>
  </body>
  <script>
    /**
     * e为MouseEvent实例,包含
     * {clientX: 161,clientY: 108}等属性
     **/
    function update_position(e) {
      let _t = e.target;
      if (_t.tagName.match(/^button$/i)) {
        // r为DOMRect实例,包含x/y/top/bottom/left/right等属性
        let r = _t.getBoundingClientRect();
        ["x", "y"].forEach((c) => {
          console.log(`${e[`client${c.toUpperCase()}`] - r[c]}px`);
          _t.style.setProperty(
            `--${c}`,
            `${e[`client${c.toUpperCase()}`] - r[c]}px`
          );
        });
      }
    }
    addEventListener("mouseover", update_position);
    addEventListener("mouseout", update_position);
  </script>
</html>

css中的@property

  • 语法
@property --property-name {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

@property 规则提供了一个直接在样式表中注册自定义属性的方式,而无需运行任何 JS 代码。有效的 @property 规则会注册一个自定义属性,就像 CSS.registerProperty (en-US) 函数被使用同样的参数调用了一样。

一个有效的 @property 规则代表一项自定义属性的注册,使用自定义属性名作为规则内代码序列的序部。

@property 规则中 syntax 和 inherits 描述符是必需的; 如果其中任何一项缺失,整条规则都将失效并且会被忽略。 initial-value 描述符仅在 syntax 描述符为通用 syntax 定义时是可选的,否则initial-value也是必需的——如果此时该描述符缺失,整条规则都将失效且被忽略。

实例

为 --my-color 自定义属性添加颜色值类型检测、设置默认值并且设置属性值不允许被继承。

使用 CSS @property 规则:

@property --my-color {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

使用 JavaScript 中的 CSS.registerProperty (en-US)函数:

window.CSS.registerProperty({
  name: "--my-color",
  syntax: "<color>",
  inherits: false,
  initialValue: "#c0ffee",
});

image.png

参考链接