js動態修改@keyframes


css3中@keyframes是寫死的,如果需要動態修改則需要js,其實操作起來也很簡單,只是一些用到了一些不常用的api

1、獲取頁面樣式表並查找keyframes所在的styleSheet

2、刪除原來的styleSheet里的動畫幀

3、添加js動態修改過后的動畫幀

實現三個步驟的代碼

1、關於獲取styleSheet這里給出了一個通用方法

function findKeyframesRule(rule) {
  //此處過濾非同源的styleSheet,因為非同源的無法訪問cssRules,會報錯
  var ss = Array.from(document.styleSheets).filter((styleSheet) => !styleSheet.href || styleSheet.href.startsWith(window.location.origin))
  for (var i = 0; i < ss.length; ++i) {
    for (var j = 0; j < ss[i].cssRules.length; ++j) {
      if (ss[i].cssRules[j].type === window.CSSRule.KEYFRAMES_RULE && ss[i].cssRules[j].name === rule) {
        return ss[i]
      }
    }
  }
  return null
}

遍歷獲取styleSheet過程中如果遇到“Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules”錯誤說明你的網頁引入了跨域的css資源,

具體解決方法已經在代碼中注釋,關於這個問題詳細可以參考:https://medium.com/better-programming/how-to-fix-the-failed-to-read-the-cssrules-property-from-cssstylesheet-error-431d84e4a139

大概內容我截圖了:

 

 

 

 

 

 2、調用deleteRule刪除對應規則,不熟悉這個api的可以參考mdn

mdn鏈接:https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleSheet/insertRule

const kfs =findKeyframesRule('animationName') 
kfs.deleteRule(index)
//index是styleSheet里你要刪除那一條的數組里對應的index

3、insertRule添加新的規則,具體參考mdn

   kfs.insertRule(`@keyframes animationName {
            0% {
                top: 0px;
                opacity: 1;
            }
            98% {
                top: -10px;
                opacity: 1;
            }
            100% {
                top: -20px;
                opacity: 0;
            }
        }`)

如果沒生效,js獲取下dom元素,更新下元素的animation樣式設置

 

參考:

https://css-tricks.com/controlling-css-animations-transitions-javascript/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM