本文主要是介绍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.clientXconst y = e.clientY// 计算了按钮相对于其父元素(body)的偏移量,即按钮顶部和左侧的位置。const buttonTop = e.target.offsetTopconst buttonLeft = e.target.offsetLeft// 计算了鼠标点击位置相对于按钮的内部位置,即点击位置距离按钮顶部和左侧的距离。const xInside = x - buttonLeftconst yInside = y - buttonTop// 创建spanconst 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)})
})
这篇关于day20-Button Ripple Effect(按钮涟漪效应)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!