我正在尝试自行建立涟漪效应,如下所示:
function onMenuClick(e) {
var dom = e.currentTarget;
var x = e.pageX;
var y = e.pageY;
var rippleDiv = document.createElement("div");
var domTokenList = rippleDiv.classList;
domTokenList.add("ripple");
rippleDiv.setAttribute("style", "top:" + (String(y) + ("px; left:" + (String(x) + "px;"))));
dom.appendChild(rippleDiv);
setTimeout((function () {
dom.removeChild(rippleDiv);
return /* () */0;
}), 900);
return /* () */0;
}
body {
background-color: coral;
}
.topbar-menu-on-mobile {
display: flex;
border-radius: 50%;
width: 50px;
height: 50px;
align-items: center;
justify-content: center;
background-color: #24344b;
margin-left: 15px;
overflow: hidden;
}
.fa-bars {
color: #2db9ba;
}
.ripple {
position: absolute;
opacity: 0;
border-radius: 50%;
width: 2px;
height: 2px;
background-color: #FFFFFF;
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-name: ripple;
animation-name: ripple;
}
@keyframes ripple {
0% {
opacity: 1;
}
100% {
transform: scale(165);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Ripple test</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
crossorigin="anonymous" />
</head>
<body>
<a onclick="onMenuClick(event)" class="topbar-menu-on-mobile">
</a>
</body>
</html>
当我单击圆时,波纹效果超过了圆。我该如何预防?
答案 0 :(得分:1)
将position:relative
添加到a
,以便您可以使用overflow:hidden
,因为波纹div将相对于a
定位。然后根据元素的位置调整JS代码以更正div
的位置。
function onMenuClick(e) {
var dom = e.currentTarget;
var elemRect = dom.getBoundingClientRect()
var x = e.pageX - elemRect.left;
var y = e.pageY - elemRect.top;
var rippleDiv = document.createElement("div");
var domTokenList = rippleDiv.classList;
domTokenList.add("ripple");
rippleDiv.setAttribute("style", "top:" + (String(y) + ("px; left:" + (String(x) + "px;"))));
dom.appendChild(rippleDiv);
setTimeout((function() {
dom.removeChild(rippleDiv);
return /* () */ 0;
}), 900);
return /* () */ 0;
}
body {
background-color: coral;
}
.topbar-menu-on-mobile {
display: flex;
border-radius: 50%;
width: 50px;
height: 50px;
align-items: center;
justify-content: center;
background-color: #24344b;
margin-left: 15px;
overflow: hidden;
position:relative;
}
.ripple {
position: absolute;
opacity: 0;
border-radius: 50%;
width: 2px;
height: 2px;
background-color: #FFFFFF;
animation-duration: 1s;
animation-name: ripple;
}
@keyframes ripple {
0% {
opacity: 1;
}
100% {
transform: scale(165);
}
}
<a onclick="onMenuClick(event)" class="topbar-menu-on-mobile">
</a>