|
这是一个CSS实现的卡片悬停交互效果,当鼠标悬停在卡片上时,会出现一个随着鼠标移动而移动的光圈。
主要实现原理是通过JavaScript获取鼠标的X/Y轴坐标,并使用CSS的radial-gradient函数和自定义属性来动态更新光圈的位置,从而创建出这种交互效果。
源代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <style>
- :root {
- --bg-color: rgb(20, 20, 20);
- --card-color: rgb(23, 23, 23);
- }
- body {
- align-items: center;
- background-color: var(--bg-color);
- display: flex;
- height: 100vh;
- justify-content: center;
- margin: 0px;
- overflow: hidden;
- padding: 0px;
- }
- #cards {
- display: flex;
- flex-wrap: wrap;
- gap: 8px;
- max-width: 916px;
- width: calc(100% - 20px);
- }
- #cards:hover > .card::after {
- opacity: 1;
- }
- .card {
- background-color: rgba(255, 255, 255, 0.1);
- border-radius: 10px;
- cursor: pointer;
- display: flex;
- height: 260px;
- flex-direction: column;
- position: relative;
- width: 300px;
- }
- .card::before {
- background: radial-gradient(
- 800px circle at var(--mouse-x) var(--mouse-y),
- rgba(255, 255, 255, 0.06),
- transparent 40%
- );
- z-index: 3;
- }
- .card:hover::before{
- opacity: 1;
- }
- .card::before,
- .card::after {
- border-radius: inherit;
- content: "";
- height: 100%;
- left: 0px;
- opacity: 0;
- position: absolute;
- top: 0px;
- transition: opacity 500ms;
- width: 100%;
- }
- .card::before {
- background: radial-gradient(
- 800px circle at var(--mouse-x) var(--mouse-y),
- rgba(255, 255, 255, 0.06),
- transparent 40%
- );
- z-index: 3;
- }
- .card::after {
- background: radial-gradient(
- 600px circle at var(--mouse-x) var(--mouse-y),
- rgba(255, 255, 255, 0.3),
- transparent 40%
- );
- z-index: 1;
- }
- .card > .card-content {
- background-color: var(--card-color);
- border-radius: inherit;
- display: flex;
- flex-direction: column;
- flex-grow: 1;
- inset: 1px;
- padding: 10px;
- position: absolute;
- z-index: 2;
- }
- </style>
- </head>
- <body>
- <div id="cards">
- <div class="card">
- <div class="card-content"></div>
- </div>
- <div class="card">
- <div class="card-content"></div>
- </div>
- <div class="card">
- <div class="card-content"></div>
- </div>
- </div>
- </body>
- <script>
- document.getElementById("cards").onmousemove = e => {
- for(const card of document.getElementsByClassName("card")) {
- const rect = card.getBoundingClientRect(),
- x = e.clientX - rect.left,
- y = e.clientY - rect.top;
- card.style.setProperty("--mouse-x", `${x}px`);
- card.style.setProperty("--mouse-y", `${y}px`);
- };
- }
- </script>
- </html>
复制代码
|
|