JS动画
一、JS结合CSS实现动画
1、通过事件修改指定的样式,形成过渡的第二状态
<style>
#div {
width: 200px;
height: 200px;
background: red;
transition: .2s;
}
</style>
<div id="div"></div>
<script>
div.onclick = function() {
this.style.width = '400px';
}
</script>
2、通过事件修改指定的类名,形成过渡的第二状态
<style>
.div {
width: 200px;
height: 200px;
background: red;
transition: .2s;
}
.div.active {
transform: scale(1.2);
}
</style>
<div id="div" class="div"></div>
<script>
div.onclick = function() {
var t_name = "active"
var c_name = this.className;
if (!c_name.match(t_name)) {
this.className += " " + t_name;
} else {
this.className = c_name.replace(" " + t_name, "");
}
}
</script>
二、JS通过定时器实现动画
js动画例子
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>js动画</title>
<style type="text/css">
.box {
width: 200px;
height: 200px;
background-color: red;
transition: .3s;
}
.box.r {
border-radius: 50%;
}
.box.h {
height: 400px;
}
</style>
</head>
<body>
<button class="btn1">变长</button>
<button class="btn2">切换宽度</button>
<button class="btn3">切换边界圆角</button>
<button class="btn4">切换高度</button>
<button class="btn5">变短</button>
<div class="box"></div>
</body>
<script type="text/javascript">
var box = document.querySelector('.box');
var b1 = document.querySelector('.btn1');
b1.onclick = function () {
box.style.width = "400px";
}
var b5 = document.querySelector('.btn5');
b5.onclick = function () {
box.style.width = "200px";
// console.log(box.style.width);
}
var b2 = document.querySelector('.btn2');
var b3 = document.querySelector('.btn3');
var b4 = document.querySelector('.btn4');
b2.onclick = function () {
var width = getComputedStyle(box, null).width;
if (width.match("200px")) {
box.style.width = "400px";
} else {
box.style.width = "200px";
}
}
b3.onclick = function () {
var c_name = box.className;
console.log(c_name);
// 可能是'box' | 'box h' | 'box r' | 'box h r'
// if (c_name == 'box') {
if (!c_name.match("r")) {
box.className += " r";
} else {
// 不是直接切回box
// box.className = "box";
// 而且去掉r
box.className = c_name.replace(" r", "");
}
}
b4.onclick = function () {
var c_name = box.className;
// 没有h类名, 单独添加h类名,反之去除h类名
if (!c_name.match("h")) {
box.className += " h";
} else {
box.className = c_name.replace(" h", "");
}
}
</script>
</html>