最近做需求,页面有个固定的红包icon,有个需求点是这样子的:(1)页面静止时,红包icon完全展示且抖动;(2)页面滑动时,红包icon贴边收起。
本来打算通过监听 touchmove 和 touchend 事件来实现这个功能点,但效果不理想,最终采用监听 scroll 事件并搭配定时器实现。以下是具体代码:
jsx文件
import React, {useEffect, useRef} from 'react';
import throttle from 'lodash/throttle';
const RedPacketIcon = (props) => {
const timer = useRef(null);
useEffect(() => {
window.addEventListener('scroll', scrollListener);
return () => {
clearTimeout(timer.current);
window.removeEventListener('scroll', scrollListener);
};
}, []);
// 监听页面滚动
const scrollListener = throttle (() => {
clearTimeout(timer.current);
const el = document.querySelector('.redpacket-icon');
el.classList.remove('shaking'); // 页面滑动时,红包icon贴边收起
timer.current = setTimeout(() => {
el.classList.add('shaking'); // 页面静止时,红包icon完全展示且抖动(1.2s)
}, 1200);
}, 500);
return (
<div className='redpacket-icon shaking'>
<img src={require('./images/icon_redpacket.png')} />
</div>
);
};
css文件
.redpacket-icon {
width: 70px;
height: 86px;
position: fixed;
top: 300px;
right: -40px;
}
.shaking {
right: 0;
animation: shakingAni 1s linear infinite;
}
// 抖动动效
@keyframes shakingAni {
0% {
transform: rotate(0);
}
5% {
transform: rotate(10deg);
}
10% {
transform: rotate(0);
}
15% {
transform: rotate(-10deg);
}
20% {
transform: rotate(0);
}
25% {
transform: rotate(10deg);
}
30% {
transform: rotate(0);
}
35% {
transform: rotate(-10deg);
}
40% {
transform: rotate(0);
}
100% {
transform: rotate(0);
}
}