【问题标题】:Second event [onClick] does not work第二个事件 [onClick] 不起作用
【发布时间】:2016-05-01 18:26:29
【问题描述】:

我在 oen 元素上得到了 2 个事件 [mousedown, click],但是当我单击图像旁边的 [它在元素内部] 时,第二个事件才起作用...我无话可说 :)

这是一个代码:codepen.io/Ivanowski/pen/JXeRpp

$('.ripple').on('mousedown', function(event){
  // Check if shadow exists
  if( $(this).find('.shadow').length == 0 )
    $(this).append('<span class="shadow"></span>');

  var shadow = $(this).find('.shadow');
  // Remove animation if it exists
  shadow.removeClass('animation');

  // Set shadow size
  if( !shadow.width() && !shadow.height() )
  {
    var size = Math.max($(this).outerWidth(), $(this).outerHeight());

    shadow.css({
      width: size,
      height: size
    });
  }

  // Set shadow left, top
  var x = Math.round( event.clientX - this.getBoundingClientRect().left ) - ( shadow.width() / 2 );
  var y = Math.round( event.clientY - this.getBoundingClientRect().top ) - ( shadow.height() / 2 );


  shadow.css({
    left: x+'px',
    top: y+'px'
  });

  // Start animation
  shadow.addClass('animation');
});

/*
 * It does not work
*/
$('#switcher').on('click', function(){
  console.log('aaa');
});
html
  height: 100%
body
  height: 100%
  background: #183145
  display: flex
  align-items: center
  justify-content: center
  
.swicher
  padding: 9px 5px
  cursor: pointer
  
.ripple
  overflow: hidden
  position: relative
  .shadow
    background: #fff
    border-radius: 100%
    position: absolute
    transform: scale(0)
    &.animation
      animation: ripple 0.6s linear
@keyframes ripple
  100%
    opacity: 0
    transform: scale(2.5)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="switcher" class="swicher ripple">
  <a href="#">
    <img src="http://i.imgur.com/Ed2ShTk.png" alt="" />
  </a>
</span>

尝试按下图像 - 事件不起作用。 快速按两次图像即可。

为什么会这样?我该如何解决?

【问题讨论】:

  • 您应该将任何相关代码复制到您的问题中。如果您的外部链接失效,这个问题将来对其他人没有任何用处。

标签: javascript jquery events


【解决方案1】:

MouseClick 事件正在发出,当您的鼠标按钮在按下后返回到向上状态时。 因此,从技术上讲,当向上和向下事件都在同一个元素上发出时,它会发出 mouseClick。 您的动画使用类阴影缩放元素,因此它会溢出图像。 鼠标按下会在图像上发光,但鼠标向上会在阴影元素上发光,因为它会溢出。

尽量不要立即抬起鼠标按钮,等待动画结束。你会看到点击事件也被触发了。

作为一种解决方案,您可以将 z-index: -1 添加到阴影类中。它将在图像下绘制元素,因此事件将正常工作。

【讨论】:

  • 大声笑为什么有人反对它?你能告诉我,我该如何解决它?
  • 是的,但是当我将背景添加到具有波纹效果的元素时,它就不起作用了。当我在一个元素上按两次时,你能告诉我为什么它会起作用吗? [没有 z-index]
  • 事件按以下顺序发出。第一次点击:mouseDown在swicher上发射,mouseUp在溢出的阴影上发射;第二次单击:mouseDown 在溢出的阴影上发出。动画结束。 mouseUp 在切换器上发出。在同一元素上注册的向上/向下事件对,发出 mouseClick。
猜你喜欢
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多