animate.css
<!-- 引入 animate.css -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<!-- 应用-->
<h1 class="animate__animated animate__bounce">An animated element</h1>
当 .animate__bounce 被添加到 .animate__animated 对象上时候,开始播放动画
Intersection Observer API
实现元素滚动进入视图后应用 css 动画
<h4 class="animate__animated" data-animation="animate__fadeInUp" data-animate-delay="1s;">
Animation fadeInUp with delay 1s
</h4>
<h4 class="animate__animated" data-animation="animate__bounceIn">
Animation bounceIn
</h4>
let callback = (entries, observer) => {
entries.forEach(entry => { // 递归监听参数对象
entry.boundingClientRect // 碰撞框
entry.intersectionRatio // 交叉率
entry.intersectionRect // 交叉区域
entry.isIntersecting // 交叉中
entry.rootBounds
entry.target // 被监听对象
entry.time // 时间
if(entry.isIntersecting){
var elem = entry.target
var props = elem.dataset
if(props.animation){
if(props.animateDelay){ // 读取延时
elem.classList.add('animate__delay-1s')
elem.style.setProperty('--animate-delay', props.animateDelay)
}
elem.classList.add(props.animation)
}
observer.unobserve(entry.target) // 移除监听元素
}
})
}
let options = {
root: document.querySelector('#scrollArea'), // default window // 父窗口对象
rootMargin: '0px', // default 0 // 拓展监听对象范围
threshold: 1.0 // (0 ~ 1.0) default 0 // 1 === 当完全进入画面 // 回调阈值 eg: 0, [0, 0.25, 0.75, 1]...
}
let observer = new IntersectionObserver(callback, options) // 异步监听对象
Array.from(document.querySelectorAll('.animate__animated')).forEach(elem => observer.observe(elem)) // 加入监听对象
:对于特殊人群关闭动效
CSS 媒体查询特性 prefers-reduced-motion 用于检测用户的系统是否被开启了动画减弱功能。
Don't disable the
prefers-reduced-motionmedia query