简体   繁体   English

我在我的代码中使用纯 javascript 得到未定义的错误

[英]I get undefined error using pure javascript in my code

I am trying to add a material ripple effect to an element using pure javascript using the code below.我正在尝试使用下面的代码使用纯 javascript 向元素添加材质波纹效果。 The problem is that the effect works only for the first click.问题是该效果仅适用于第一次点击。 If I try to click the button again, I get the message Uncaught TypeError: circle is undefined on my console.如果我尝试再次单击该按钮,我会在控制台上收到消息Uncaught TypeError: circle is undefined

 function createRipple(event) { const target = event.currentTarget; const circle = target.classList.add("ripple"); const ripple = circle.getElementsByClassName("ripple")[0]; if (ripple) { ripple.remove(); } } const buttons = document.getElementsByClassName("my-ripple"); for (const button of buttons) { button.addEventListener("click", createRipple); }
 .my-ripple { position: relative; overflow: hidden; display: inline-block; width: auto; padding: 1.2rem; font-family: sans; cursor: pointer; border-radius: 10px; }.ripple::after { content: ""; position: absolute; border-radius: 50%; transform: scale(0); animation: ripple 600ms linear; background-color: rgba(0, 0, 0, 0.5); top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 100px; height: 100px; } @keyframes ripple { to { transform: scale(4); opacity: 0; } }
 <div class="my-ripple">Click me</div>

classList does not return an object. classList不返回 object。 And you do not need it actually, because you already have the target instance, so fetching it again by class is not necessary.而且您实际上不需要它,因为您已经有了target实例,因此不需要通过 class 再次获取它。 Instead just remove the class from it directly with a timeout:相反,只需使用超时直接从中删除 class :

function createRipple(event) {
  const target = event.currentTarget;
  target.classList.add("ripple");
  setTimeout(function() {
    target.classList.remove("ripple");
  }, 600);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM