CSS3 触发animation和@keyframes定义的动画

重新触发CSS3 animation和@keyframes定义的动画
结合CSS3的animation和@keyframes可以给元素定义动画,定义一个标题进入的动画如下:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>重新触发CSS3 animation和@keyframes定义的动画</title>
	<style type="text/css">
		@keyframes my-animation {        
		  from {
		    opacity : 0;
		    left : -500px;
		  }
		  to {
		    opacity : 1;
		    left : 0;
		  }      
		}
		.run-animation {
		  position: relative;
		  animation: my-animation 2s ease;
		}
		#logo {
		  text-align: center;
		}
		/* @keyframes定义了效果,样式从左侧向右侧移动,由透明变为不透明。animation定义了动画,使用效果my-animation,耗时2秒,渐入。 */
	</style>
</head>
<body>
	<h2>重新触发CSS3 animation和@keyframes定义的动画</h2>
	<p>结合CSS3的animation和@keyframes可以给元素定义动画,定义一个标题进入的动画如下:</p>
	<h1 id="logo" class="run-animation">
	  你好(点击重新运行)
	</h1>
	<!-- 直接在元素上添加class run-animation,它只会运行一次。 -->
	<!-- 重新运行动画
添加了动画的元素,只会在元素第一次渲染时才会触发动画,如果需要重新动画,需要对元素进行定位操作,步骤如下:

1. 删除元素已添加的动画class
2. 对元素做定位操作
3. 添加原来的动画class
 -->
<script type="text/javascript">
	var element = document.getElementById("logo");
	// 监听触发动画的事件,如click
	element.addEventListener("click", function(e){
		e.preventDefault;
		// 1、删除动画的class
		element.classList.remove("run-animation");
		// 2、改变元素的offsetWidth
		element.offsetWidth=element.offsetWidth;
		// 3、重新添加动画的class
		element.classList.add("run-animation");
	}, false);
</script>
</body>
</html>

//需要注意的是再严格模式下,element.offsetWidth=element.offsetWidth是不生效的,替代方案:

void element.offsetWidth

猜你喜欢

转载自blog.csdn.net/gqzydh/article/details/88286347
今日推荐