day20-Button Ripple Effect(按钮涟漪效应)

50 天学习 50 个项目 - HTMLCSS and JavaScript

day20-Button Ripple Effect(按钮涟漪效应)

效果

在这里插入图片描述
在这里插入图片描述

index.html

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

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Button Ripple Effect</title>
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <!-- 按钮 -->
    <!-- ripple  涟漪-->
    <button class="ripple">点击我</button>

    <script src="script.js"></script>
</body>

</html>

style.css

/* 引入字体 */
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

* {
    box-sizing: border-box;
}

body {
    background-image: linear-gradient(blue 0%,
            skyblue 50%,
            blue 100%);
    font-family: 'Roboto', sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    overflow: hidden;
    margin: 0;
}

/* 按钮 */
button {
    background-color: rgb(0, 234, 255);
    color: #fff;
    border: 1px black solid;
    font-size: 14px;
    /* 将文本大写 */
    text-transform: uppercase;
    letter-spacing: 2px;
    padding: 20px 30px;
    overflow: hidden;
    margin: 10px 0;
    position: relative;
    outline: none;
}

/* 按钮涟漪效果 */
button .circle {
    position: absolute;
    background-color: #fff;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    transform: translate(-50%, -50%) scale(0);
    /* 动画 */
    animation: scale 0.5s ease-out;
}

/* 动画 */
@keyframes scale {
    to {
        transform: translate(-50%, -50%) scale(3);
        opacity: 0;
    }
}

script.js

// 重点是 flex transform animation position: absolute; rotate 的应用

// 1.获取元素节点
const buttons = document.querySelectorAll('.ripple');//按钮元素节点
// 2.遍历添加点击事件
buttons.forEach(button => {
    button.addEventListener('click', function (e) {
        // 鼠标的位置
        const x = e.clientX
        const y = e.clientY
        // 计算了按钮相对于其父元素(body)的偏移量,即按钮顶部和左侧的位置。
        const buttonTop = e.target.offsetTop
        const buttonLeft = e.target.offsetLeft
        // 计算了鼠标点击位置相对于按钮的内部位置,即点击位置距离按钮顶部和左侧的距离。
        const xInside = x - buttonLeft
        const yInside = y - buttonTop
        // 创建span
        const circle = document.createElement('span')
        // 添加circle样式,并设置位置
        circle.classList.add('circle')
        circle.style.top = yInside + 'px'
        circle.style.left = xInside + 'px'

        this.appendChild(circle)
        // 0.5秒后移除span,防止过多
        setTimeout(() => circle.remove(), 500)
    })
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值