在页面设置一个开始按钮,点击开始,从页面的顶部出来一个正方形,逐渐向上移动到浏览器中间停下,颜色从透明到红色,
// 再次点击开始,正方形从中心往底部移动,颜色从红色到透明
就是改变一个top和透明度(opacity),很简单吧。
动画或者过度,点击两次,用两个过度类来实现也可以
帮你写了个小demo,可以优化的点还挺多的
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Document</title>
<style>
.moveBox {
transition: all 500ms;
position: absolute;
top: -200px;
left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
background-color: red;
opacity: 0;
}
</style>
</head>
<body>
<div id="moveBox" class="moveBox"></div>
<button id="moveBtn">移动</button>
<script>
let state = 0
const moveBox = document.getElementById("moveBox")
const moveBtn = document.getElementById("moveBtn")
moveBtn.onclick = () => {
switch (state) {
case 0:
moveBox.style.top = "50%"
moveBox.style.opacity = "1"
break
case 1:
moveBox.style.top = "100%"
moveBox.style.opacity = "0"
break
}
state++
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
html,body {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
</body>
<script type="text/javascript">
// 创建按钮
var str = '<button id="btn" onClick="btnClick()">按钮</button>';
// 创建正方形
str += '<div id="sq" style="width:100px;height:100px;background-color: red;position:fixed;top:-100px;left:50%;opacity:0;transition: all .3s ease; transform: translate(-50%,-50%);"></div>';
// 把按钮和正方形添加到页面中
var body = document.getElementsByTagName('body')[0];
body.innerHTML = str;
// 按钮增加点击事件
function btnClick() {
// 获取正方形盒子
var square = document.getElementById('sq')
// 获取当前盒子的位置
var squareTop = square.style.top;
if (squareTop=='-100px') {
square.style.transition = 'all .3s ease';
square.style.top = '50%';
square.style.opacity = '1';
} else if (squareTop=='50%') {
square.style.top = '150%';
square.style.opacity = '0';
setTimeout(() => {
square.style.transition = 'all 0s ease';
square.style.top = '-100px';
square.style.opacity = '0';
},300)
}
}
</script>
</html>