每次点击触发相同的 CSS 动画 [英] Trigger same CSS animation on every click

查看:19
本文介绍了每次点击触发相同的 CSS 动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在点击时触发 CSS 动画,但每次点击后都会重新启动.我知道我可以打开和关闭动画,但我想在每次点击按钮时触发动画.此外,最初不应运行 CSS 动画.仅在点击时运行.

I'm trying to trigger a CSS animation onclick, but have it restart after each click. I know I can toggle the animation on and off, but I'd like to just trigger the animation every time the button is clicked. Also, initially the CSS animation should not run. Only run when clicked.

这是我的笔.http://codepen.io/omarel/pen/JRwpZp

HTML:

<a href="#" class="addtocart">click me</a>

Jquery:

 $('.addtocart').click(function () {  
     $(this).addClass('on');
 }); 

CSS:

.addtocart {
    position: relative;
}

    .addtocart.on {
        -webkit-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
        -moz-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
        -ms-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
        -o-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
        animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    }

@keyframes cartbtnFade {
    0% {
        opacity: 0;
        transform: translateY(-100%);
    }

    10% {
        transform: translateY(-100%);
    }

    15% {
        transform: translateY(0);
    }

    30% {
        transform: translateY(-50%);
    }

    40% {
        transform: translateY(0%);
    }

    100% {
        opacity: 1;
    }
}

推荐答案

可以在动画结束时收听,然后去掉'on'类

You can listen to when the animation ends, then remove the class 'on'

var animationEvent = 'webkitAnimationEnd oanimationend msAnimationEnd animationend';
$('.addtocart').click(function () { 
  $(this).addClass('on');
  $(this).one(animationEvent, function(event) {
    $(this).removeClass('on')
  });
}); 

$('.addtocart').click(function () { 
  $(this).addClass('on');
  $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(event) {
    $(this).removeClass('on')
  });
}); 

.addtocart {
		position:relative;
  width:100px;
  display:block;
  background-color:#000;
  color:#fff;
  padding:10px;
  text-align:center;
	}
	.addtocart.on {
    -webkit-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    -moz-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    -ms-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    -o-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
	}

@keyframes cartbtnFade {
  0% {
    opacity: 0;
    transform:translateY(-100%);
  }
  10% {
  	transform:translateY(-100%);

  }
  15% {
	  transform:translateY(0);
	}
	30% {
	  transform:translateY(-50%);
	  
	}
	40% {
	  	transform:translateY(0%);

	}
  100% {
    opacity: 1;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="addtocart">click me</a>

这篇关于每次点击触发相同的 CSS 动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆