首页 > 解决方案 > 当用户每次点击一个元素时执行一个效果

问题描述

每次用户使用 jquery 单击元素时,我如何执行此效果?

我在单击时添加了一个波纹类,但是当我第二次单击该元素时,它无法执行,因为已经添加了该类,我该如何解决这个问题?

<div class="circle-ripple"></div>
html, body {
  width: 100%;
  height: 100%;
}

body {
  background-color: #4e4e4e;
  display: flex;
  align-items: center;
  justify-content: center;

}

.circle-ripple {
  background-color: #35ffc3;
  width: 1em;
  height: 1em;
  border-radius: 50%;
}
.ripple {
    -webkit-animation: ripple 0.7s linear;
          animation: ripple 0.7s linear;
  animation-duration:0.5s;

}
@-webkit-keyframes ripple {
  0% {
    box-shadow: 0 0 0 0 rgba(101, 255, 120, 0.3), 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3);
  }
  100% {
    box-shadow: 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3), 0 0 0 8em rgba(101, 255, 120, 0);
  }
}

@keyframes ripple {
  0% {
    box-shadow: 0 0 0 0 rgba(101, 255, 120, 0.3), 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3);
  }
  100% {
    box-shadow: 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3), 0 0 0 8em rgba(101, 255, 120, 0);
  }
}
$(document).ready(function(){
  $(".circle-ripple").click(function(){
    $(this).addClass("ripple");
  });
});

标签: jqueryhtmlcss

解决方案


如果你想避免超时,你可以像这样重新插入元素(我只更改了 JavaScript):

$(document).ready(function(){
  $(".circle-ripple").click(function(){
      // reinsert div with ripple class
      const new_element = $(this).clone(true);
      new_element.addClass("ripple");
      $(this).before(new_element);
      $(this).remove();
  });
});
html, body {
  width: 100%;
  height: 100%;
}

body {
  background-color: #4e4e4e;
  display: flex;
  align-items: center;
  justify-content: center;

}

.circle-ripple {
  background-color: #35ffc3;
  width: 1em;
  height: 1em;
  border-radius: 50%;
}
.ripple {
    -webkit-animation: ripple 0.7s linear;
          animation: ripple 0.7s linear;
  animation-duration:0.5s;

}
@-webkit-keyframes ripple {
  0% {
    box-shadow: 0 0 0 0 rgba(101, 255, 120, 0.3), 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3);
  }
  100% {
    box-shadow: 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3), 0 0 0 8em rgba(101, 255, 120, 0);
  }
}

@keyframes ripple {
  0% {
    box-shadow: 0 0 0 0 rgba(101, 255, 120, 0.3), 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3);
  }
  100% {
    box-shadow: 0 0 0 1em rgba(101, 255, 120, 0.3), 0 0 0 3em rgba(101, 255, 120, 0.3), 0 0 0 5em rgba(101, 255, 120, 0.3), 0 0 0 8em rgba(101, 255, 120, 0);
  }
}
<div class="circle-ripple"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读