今天看到一個css動畫樣式,然后打算封裝一個這個css樣式。
我用的react組件,然后map了我要的全部盒子
遇到了困難,我打印e和this,都沒有我想用的東西。
持續性困惑。
陷入沉思和沉睡。
然后不停打印refs。。。
天啊,我在干什么。我執着地尋找style。。。
我在return的盒子里加了一個style,然后打印了style,的確可以改變css屬性
我突然意識到,我需要打印更原始,或者說更底層的一些東西
於是我開始打印window和document,笨蛋啊,操作dom啊
我打印了document,然后開始點方法打印styleSheets
是個數組,然后百度了styleSheets,
應用於文檔的所有樣式表是通過document.styleSheets集合來表示。通過這個集合的length屬性可以獲知文檔中樣式表的數量,而通過方括號語法或itme()方法可以訪問每一個樣式表。
還查看了這個parentStyleSheet:
parentStyleSheet:在當前樣式表是通過@import導入的情況下,這個屬性是一個指向導入它的樣式表的指針。
我要寫動畫!我要寫動畫!
我要怎么才能用上它呢?
this.refs[0].style.animation='myMove 5s'
document.styleSheets[0].insertRule(`@keyframes myMove{from{ color:'red' }to{color:'blue'}`,0)
insertRule是個啥呢。。。
這個網址必讀,有詳細介紹。
格式有了,然后加上方法的調用以及停止,代碼如下
1 import React, { Component } from 'react' 2 3 export default class OneDemo extends Component { 4 5 //構造方法,創建組件時調用 6 constructor(props){ 7 super(props) 8 this.state={ 9 data:[1,2,3,4,5,'',6,7,8,9,'',0,2,1,3,4,5,6,7,'',5,4,3,2,1,2,3,9] 10 } 11 } 12 13 componentDidMount(e) { 14 //拿到一個this.refs的數量,是個遍歷key的數組,numArr 15 let numArr = Object.keys(this.refs) 16 //因為是順序排列的,要最后一位,也等於長度減一 17 let num = numArr.length-1 18 let startNum = 0 19 //我在函數里拿到num,放到state里唄 20 this.state.startNum=startNum 21 this.state.endNum = num 22 //設一個時間函數timer,1000毫秒執行一次 23 this.state.timer=setInterval(this.fn,300) 24 } 25 fn=()=>{27 let animationStyle = this.refs[this.state.startNum].style 28 animationStyle.display='inline-block' 29 document.styleSheets[0].insertRule(`@keyframes mymove{ 30 0%{ color:white;transform:rotate(0deg) translateY(0px)} 31 70%{color:black;transform:rotate(180deg) translateY(-24px)} 32 100%{ color:#666;transform:rotate(360deg) translateY(0px)} }`,0) 33 animationStyle.animation='mymove 1s linear forwards' 34 //遞增 35 this.state.startNum++ 36 //清除timer 37 if(this.state.startNum==this.state.endNum+1){ 38 clearInterval(this.state.timer) 39 } 40 } 41 42 render() { 43 return ( 44 <div className="OneDemo"> 45 { 46 this.state.data.map((v,i)=>{ 47 if(v===''){ 48 return( 49 <span key={i} ref={i} style={{display:'inline-block',width:'6px',height:'24px'}}> </span> 50 ) 51 }else{ 52 return( 53 <span key={i} ref={i} style={{display:'inline-block',width:'6px',height:'24px'}}>{v}</span> 54 ) 55 } 56 57 }) 58 } 59 </div> 60 ) 61 } 62 }
你復制一下,就知道這個循環渲染文字加動畫,還是不錯滴!