HTML&CSS:美到眩晕的流光按钮

539 阅读2分钟

这段 HTML 代码创建了一个具有动态颜色旋转效果的按钮

演示效果

HTML&CSS

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>公众号关注:前端Hardy</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #212121;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }
        button {
            background-image: linear-gradient(oklch(59% 56% 259deg), oklch(59% 56% 259deg)), conic-gradient(from var(--angle-to-the-dangle), oklch(59% 56% 259deg) 0deg, white 20deg, oklch(59% 56% 259deg) 40deg);
            background-clip: padding-box, border-box;
            background-position: center center;
            background-size: 170px 500px;
            border-radius: 12px;
            color: white;
            padding: 1rem 2rem;
            font-size: 1.5rem;
            border: 2px solid transparent;
        }
    </style>
</head>

<body>
    <button id="rotateButton">添加资源</button>
    <script>
        const button = document.getElementById('rotateButton');
        let angle = 0;
        function rotateColors() {
            angle = (angle + 2) % 360;
            button.style.setProperty('--angle-to-the-dangle', `${angle}deg`);
            requestAnimationFrame(rotateColors);
        }
        rotateColors();
    </script>
</body>

</html>

HTML 结构

  • rotateButton:定义一个按钮,文本为“添加资源”,ID 为“rotateButton”.

CSS 样式

  • body 样式:设置页面的边距为 0,背景颜色为深灰色,使用 flex 布局使内容居中显示,页面高度为视口高度(100vh).
  • button 样式:定义按钮的背景图像、剪裁、位置、尺寸、边框、颜色、内边距和字体大小.
  • background-image:使用线性渐变和圆锥渐变组合,创建一个动态的颜色旋转效果.
  • linear-gradient(oklch(59% 56% 259deg), oklch(59% 56% 259deg)):线性渐变,颜色从一个角度到另一个角度变化.
  • conic-gradient(from var(--angle-to-the-dangle), oklch(59% 56% 259deg) 0deg, white 20deg, oklch(59% 56% 259deg) 40deg):圆锥渐变,颜色从一个角度到另一个角度变化,使用自定义属性--angle-to-the-dangle 控制旋转角度.
  • background-clip:设置背景图像的剪裁区域,padding-box 和 border-box 分别表示内边距区域和边框区域.
  • background-position:设置背景图像的位置为居中.
  • background-size:设置背景图像的尺寸为 170px 500px.
  • border-radius:设置按钮的圆角大小为 12px.
  • color:设置按钮文本的颜色为白色.
  • padding:设置按钮的内边距为 1rem 2rem.
  • font-size:设置按钮文本的字体大小为 1.5rem.
  • border:设置按钮的边框为 2px 宽,颜色为透明.

JS

  • 获取按钮元素.
  • 定义变量 angle 用于存储旋转角度.
  • rotateColors 函数:更新旋转角度,设置按钮的自定义属性--angle-to-the-dangle,使用 requestAnimationFrame 递归调用自身,实现颜色的动态旋转效果.
  • 调用 rotateColors 函数开始颜色旋转动画.