背景:
上篇博文我们讲到了一个dom API(animate),虽然很好用,但它在IE11上却不支持,今天就简单讲一下,如何在IE11中使用动画,其实可以理解为换种方式实现,这里我会总结列出我遇到的一些坑
假如在实际项目中要支持IE11浏览器,但该animate属性又不兼容,此时我们可以改写成用css 的animation API 来实现动画…
模拟需求:我们还是实现一个无限滚动列表为demo
DEMO
// js文件
// index.jsx
import React, { createRef, Component } from 'react';
import './index.css';
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
class RollList extends Component {
constructor(props) {
super(props)
this.ref1 = createRef();
this.ref2 = createRef();
}
componentDidMount() {
const height = this.ref1.current.clientHeight;
this.ref1.current.style.animation = `animateName1 ${60* height}ms infinite linear`
this.ref2.current.style.animation = `animateName1 ${60* height}ms infinite linear`
}
onMouseEnter = () => {
this.ref1.current.style.animationPlayState = 'paused'
this.ref2.current.style.animationPlayState = 'paused'
}
onMouseLeave = () => {
this.ref1.current.style.animationPlayState = ''
this.ref2.current.style.animationPlayState = ''
}
render() {
return (
<div className='boxOut' onMouseEnter ={this.onMouseEnter } onMouseLeave ={this.onMouseLeave }>
<div className='box ' ref={this.ref1}>
{arr.map(item => (
<div className='items'>{item}</div>
))}
</div>
<div className='box' ref={this.ref2}>
{arr.map(item => (
<div className='items'>{item}</div>
))}
</div>
</div>
)
}
}
export default RollList;
========================================================================================================
// index.css
.boxOut {
width: 600px;
height: 300px;
background: yellowgreen;
overflow: hidden;
position: relative;
}
.items {
width: 600px;
height: 40px;
}
.box {
position: absolute;
}
// 动画1
@keyframes animateName1 {
from{
transform:translateY(0)
}
to{
transform:translateY(-100%)
}
}
// 动画2
@keyframes animateName2 {
from{
transform:translateY(100%)
}
to{
transform:translateY(0)
}
}
代码解析:
1、这里应用到了animationPlayState 属性来控制元素的动画是否暂停和播放,paused为暂停,“”为执行动画
2、还有一个点就是animation属性我我们通过js动态设置上去的,而不是在css中直接写死,这是因为这个animation属性在IE10-11浏览器中一旦被设置赋值,就不能再改变,所以我们就不在css中初始设置了