我有一个简单的 div,我要在其中添加一个子项。我正在尝试使用 evt.clientX 和 clientY 计算 child 的位置。相反,我似乎正在获取包含元素的坐标,即使函数在 div 上也是如此。
如何获取 div 而不是父级的点击事件?我对事件继承知之甚少,即使那是所谓的事件继承。
代码如下:
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>
最佳答案
您的代码的问题是 clientX 是相对于整个页面,而不是事件。
一个快速的解决方案是更改 x 的计算以减去元素的 x 位置。
x = evt.clientX;
y = evt.clientY;
const rect = evt.target.getBoundingClientRect()
x -= rect.x;
y -= rect.y;
关于javascript - Js鼠标点击事件似乎在错误的元素上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49084129/