此处是一个小Demo,只要掌握了思想,其他都是融会贯通的哟
可以复制代码看一下效果喔
HTML
<p id="showp">一个简单的p标签</p>
CSS
#showp {
width: 500px;
height: 350px;
background-color: aqua;
margin: 1000px auto 200px auto;
transform: translateX(-100%);
opacity: 0;
}
JS
// onscroll事件
window.onscroll = function(e) {
var show = document.getElementById("showp");
// 获取浏览器窗口可视化高度
var clientH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// 获取showp元素顶部到浏览器窗口顶部的距离
var showTop = show.getBoundingClientRect().top;
// 如果距离小于可视化窗口高度,就给showp元素添加动画效果
let x = ((clientH-showTop)*1)/350;
if (showTop <= clientH) {
showp.style.opacity = `${x}`;
showp.style.transform = `translateX(-${(1-x)*100}%)`;
}
};