通过JavaScript调用CSS动画

通过JavaScript调用CSS动画

    • 案例一:通过按钮开始和停止动画
    • 案例二:通过定时器停止动画

案例一:通过按钮开始和停止动画


<html>
	<head>
		<meta charset="utf-8">
		<title>title>
		<style>
		.animation {
		    animation: move 2s infinite alternate;
			border:1px solid;
			width:100px;
			height:100px;
			margin-top:50px;
		}
		  
		@keyframes move {
		    0% {
				transform: rotate(0deg) translate(-100px, 0); ;
		    }
		    100% {
				transform: rotate(360deg) translate(100px, 0);
		    }
		}
		
		.btn:hover{
			cursor: pointer;
		}
		style>
	head>
	<body>
		<div class="btn">stopdiv>
		<div class="animation">div>
		<script type="text/javascript">
			document.querySelector('.btn').addEventListener('click', function() {
                //querySelector() 方法返回文档中匹配指定 CSS 选择器的第一个元素
			    let btn = document.querySelector('.btn');
			    let elem = document.querySelector('.animation');
			    let state = elem.style['animationPlayState'];
			      
			    if(state === 'paused') {
			        elem.style['animationPlayState'] = 'running';
			        btn.innerText = 'stop';
			    } else {
			        elem.style['animationPlayState'] = 'paused';
			        btn.innerText = 'play';
			    }
			});			
		script>
	body>
html>

案例二:通过定时器停止动画


<html>
	<head>
		<meta charset="utf-8">
		<title>title>
		<style>
		.animation {
		    animation: move 2s linear infinite alternate;
			border:1px solid;
			width:100px;
			height:100px;
		}
		  
		@keyframes move {
		    0% {
				transform: rotate(0deg);
		    }
		    100% {
				transform: rotate(360deg);
		    }
		}
		style>
	head>
	<body>
		<div class="animation">div>
		<script type="text/javascript">
			// 设置动画在600毫秒后暂停,这个时间值可以根据情况(要停止的位置)自己设置
			setInterval("pausedMove()",600);
			function pausedMove(){
				let elem = document.querySelector('.animation');
				//这样写也可以:elem.style.animationPlayState = 'paused';
				elem.style['animationPlayState'] = 'paused';
			}
		script>
	body>
html>

你可能感兴趣的:(CSS)