innerHTML值更新问题波纹效果按钮

问题描述 投票:0回答:1

我想知道,为什么值没有更新,我的意思是点击事件的监听器本身没有执行

如果我删除

prevRippleEl.remove()
线,那么它可以正常工作,涟漪效应有效并且价值也会增加,所以,我想知道
prevRippleEl.remove()
为何以及如何导致问题。

请记住,我不需要那个解决方案,我已经有了解决方案。

const ripple_span = document.createElement('span');
const link = document.getElementById('link');
const valueSpan = document.getElementById('value');
let value = 0
link.appendChild(ripple_span);
link.addEventListener('mousedown', (e) => {
  createRipple(e);
});


function createRipple(e) {
  const prevRipple = ripple_span.querySelector('.ripple_effect');
  if (prevRipple) prevRipple.remove();
  const rippleInnerSpan = document.createElement('span');
  const targetElRect = link.getBoundingClientRect();
  const diameter = Math.max(targetElRect.width, targetElRect.height);
  const x = e.clientX - targetElRect.left;
  const y = e.clientY - targetElRect.top;
  rippleInnerSpan.style.top = `${y}px`;
  rippleInnerSpan.style.left = `${x}px`;
  rippleInnerSpan.classList.add('ripple_effect');
  ripple_span.appendChild(rippleInnerSpan);
  setTimeout(() => {
    rippleInnerSpan.style.transform = `scale(${diameter * 2.5})`;
  }, 0);

  link.addEventListener('mouseup', () => {
    rippleInnerSpan.style.opacity = '0';
  });

}

link.addEventListener('click', () => {
  value++;
  valueSpan.innerHTML = value;
});
* {
  font-family: sans-serif;
  font-size: 1rem;
}

.ripple_effect {
  position: absolute;
  width: 1px;
  height: 1px;
  border-radius: 50%;
  background-color: rgba(0, 92, 187, 0.3);
  transform: scale(0);
  transition: all 0.4s ease-in-out;
}

.ripple_targetEl {
  display: inline-flex;
  align-items: center;
  background-color: transparent;
  position: relative;
  z-index: 10;
  overflow: hidden;
  text-decoration: none;
  cursor: pointer;
  color: rgb(0, 92, 187);
  transition: all 0.1s ease-in-out;
}

.ripple_targetEl:hover {
  background-color: rgba(0, 92, 187, 0.15);
}

a {
  padding: 0.3rem 0.6rem;
  border-radius: 10px;
}
<span id="value"></span><br>
<a href="#" id="link" class="ripple_targetEl">Click</a>

javascript mouseevent clickevent
1个回答
0
投票

您的点击事件处理程序位于您删除的元素上。

从包装器中代替委托

container.addEventListener('click', (e) => {
  value++;
  valueSpan.innerHTML = value;
   createRipple(e.target);
});
© www.soinside.com 2019 - 2024. All rights reserved.