<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#show {
width: 500px;
height: 350px;
background-color: aqua;
margin: 1000px auto 0 auto;
}
.show {
animation: loading 2s linear;
}
@keyframes loading {
from {
opacity: 0;
transform: translate(-100%, 0);
}
to {
opacity: 1;
transform: translate(0, 0);
}
}
</style>
</head>
<body>
<p id="show"></p>
<script>
// classList.add( newClassName );
// 添加新的类名,如已经存在,取消添加
// classList.contains( oldClassName );
// 确定元素中是否包含指定的类名,返回值为true 、false;
// classList.remove( oldClassName );
// 移除已经存在的类名;
// classList.toggle( className );
// 如果classList中存在给定的值,删除它,否则,添加它;
// classList.replace( oldClassName,newClassName );
// 类名替换
// window.onscroll = function () {
// let show = document.getElementById('show');
// // 获取浏览器窗口可视化高度
// let clientH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// // 获取show元素顶部到浏览器窗口顶部的距离
// let showTop = show.getBoundingClientRect().top;
// // 如果距离小于可视化窗口高度,就给show元素添加动画效果
// if (showTop <= clientH) {
// show.classList.add('show');
// } else {
// show.classList.remove('show');
// }
// };
window.addEventListener('scroll', () => {
let show = document.getElementById('show');
// 获取浏览器窗口可视化高度
let clientH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// 获取show元素顶部到浏览器窗口顶部的距离
let showTop = show.getBoundingClientRect().top;
// 如果距离小于可视化窗口高度,就给show元素添加动画效果
if (showTop <= clientH) {
show.classList.add('show');
} else {
show.classList.remove('show');
}
})
</script>
</body>
</html>