我正在尝试创建简单的涟漪效果。当我向元素 newClick 添加类时,我预期会产生连锁反应。得到了 troblued,因为附加类是立即的,我看不到效果。你能帮我吗?
const button = document.querySelector('.button');
const handleClick = (e) => {
const newClick = document.createElement('div');
newClick.classList.add('point');
newClick.style.top = `${e.offsetY}px`;
newClick.style.left = `${e.offsetX}px`;
newClick.classList.add('active');
button.appendChild(newClick);
};
button.addEventListener('click', handleClick);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #000;
}
.button {
position: relative;
background-color: #7c1a76;
border: none;
padding: 1em 2em;
color: #fff;
letter-spacing: 1px;
text-transform: uppercase;
cursor: pointer;
overflow: hidden;
}
.point {
position: absolute;
width: 5px;
height: 5px;
border-radius: 50%;
opacity: 1;
background-color: #fff;
transform: scale(1);
transition: transform 0.5s, opacity 0.5s;
}
.active {
transform: scale(10);
background-color: #fff;
opacity: 0;
transition: transform 0.5s, opacity 0.5s;
}
<!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="css/style.css" />
</head>
<body>
<button class="button">click me</button>
<script src="script.js"></script>
</body>
</html>
我花了几个小时解决这个麻烦。为什么我看不到转换效果?这是教程中的项目,但我想用我的方式来做。
它不起作用,因为您在添加类后向按钮添加元素。
要解决此问题,您必须在按钮中添加 clickContainer,因为您的代码会在每个单击事件上创建 newClick 元素。 好吗?
像这样
<button>
click me
<div class='clickContainer'/>
</button>
然后,按照以下步骤操作。
-创建新的Click 元素
-清空clickContainer
-将 newClick 元素附加到 clickContainer
-将类添加到newClick
然后就可以了。
你使用了过渡。
我认为它不适合这个问题,因为在循环之后 更大,它的不透明度为0,但它保持它的大小。
而且,你为此使用了 2 个类。
不太好。
所以我认为使用动画既简单又合适。
我在下面添加代码。
-脚本
const button = document.querySelector(".button");
const handleClick = (e) => {
if (e.target.id !== "button") return;
const clickContainer = document.querySelector("#clickContainer");
clickContainer.innerHTML = "";
const newClick = document.createElement("div");
clickContainer.appendChild(newClick);
newClick.classList.add("point");
newClick.style.top = `${e.offsetY}px`;
newClick.style.left = `${e.offsetX}px`;
};
-CSS
.point {
position: absolute;
width: 0px;
height: 0px;
border-radius: 50%;
background-color: #fff;
animation-name: ripple;
animation-duration: 0.5s;
animation-timing-function: ease-out;
}
@keyframes ripple {
0% {
width: 5px;
height: 5px;
opacity: 1;
transform: scale(1);
}
100% {
width: 5px;
height: 5px;
transform: scale(20);
opacity: 0;
}
}