我有一个简单的div,我正在添加一个孩子。我正在尝试使用evt.clientX和clientY来计算孩子的位置。相反,我似乎得到了包含元素的坐标,即使函数在div上也是如此。
我怎样才能获得div而不是父级的click事件?我不太了解事件继承,如果这甚至是它所谓的。
以下是代码:
function initRipple() {
//qck define
let rcont;
rcont = Array.from(document.getElementsByClassName('ripple'));
rcont.forEach(function(el) {
el.addEventListener('click', function(evt) {
ripple(el, evt);
});
});
}
function ripple(el, evt) {
// qck def
let cir, x, y;
// assign values
cir = document.createElement('div');
x = evt.clientX;
y = evt.clientY;
// modify circle attributes / position
cir.classList.add('ripple-bubble');
cir.style.left = `${ x - 12 }px`;
cir.style.top = `${ y - 12 }px`;
cir.addEventListener('animationend', function() {
let oldChild = el.removeChild(cir);
});
el.appendChild(cir);
}
initRipple();
body {background-color: #555}
#tablinks {
display: inline-block;
list-style-type: none;
position: absolute;
top: 0;
height: 100%;
display: flex;
}
#tablinks #tablinks-line {
height: 3px;
position: absolute;
bottom: 0;
left: 0;
min-width: 24px;
background-color: #6DADFF;
transition: all 0.3s ease;
pointer-events: none;
transform: translateZ(0);
}
#tablinks .tablink {
height: 56px;
line-height: 56px;
color: rgba(255, 255, 255, 0.7);
}
#tablinks .tablink.active {
color: #fff;
}
#tablinks .tablink a {
display: inline-block;
height: 56px;
line-height: 56px;
text-decoration: none;
padding: 0 24px;
font-size: 13px;
color: inherit;
outline: none;
font-family: robotomedium;
font-weight: 100;
}
.ripple {
position: relative;
overflow: hidden;
}
.ripple .ripple-bubble {
animation: ripple-effect 1s ease forwards;
width: 24px;
height: 24px;
position: absolute;
transform: translateZ(0);
background-color: rgba(255, 255, 255, 0.2);
border-radius: 50%;
pointer-events: none;
opacity: 0.7;
}
@keyframes ripple-effect {
from {
transform: scale(1);
opacity: 0.7;
}
to {
transform: scale(12);
opacity: 0;
}
}
<ul id="tablinks">
<li class="tablink ripple"><a href="#">TAB 1</a></li>
<!--
-->
<li class="tablink ripple"><a href="#">TAB 2</a></li>
<!--
-->
<li class="tablink ripple"><a href="#t">TAB 3</a></li>
</ul>
答案 0 :(得分:0)
您的代码存在的问题是clientX相对于整个页面而不是事件。
快速解决方案是更改x的计算以提取元素的x位置。
x = evt.clientX;
y = evt.clientY;
const rect = evt.target.getBoundingClientRect()
x -= rect.x;
y -= rect.y;