Stack CSS Transitions using multiple classes without overriding

后端 未结 1 1106
轮回少年
轮回少年 2021-01-17 11:25

I want to use multiple classes to optionally add transitions. Instead of stacking, the previous is getting overridden.

.container { transition: margin .2s;          


        
相关标签:
1条回答
  • 2021-01-17 12:18

    JavaScript could be a cleaner solution as you only need to have 1 CSS rule (the original rule).

    If you know the position of you're rule you can do the following.

    //First Save The Original Rule
    
    var originalRule = document.styleSheets[0].cssRules[3].cssText;
    
    //Save also the original Hover Rule
    
    var originalHover = document.styleSheets[0].cssRules[4].cssText;
    

    Now originalRule will contain this:

    .container{
       ...
       transition: margin .2s;
       ...
    }
    

    And originalHover will contain this:

    .container:hover{
       ...
       margin: 10px 0;
       ...
    }
    

    to simply add another transition effect, you can do the following.

    document.styleSheets[0].cssRules[3].style.transitionProperty += ",background-color";
    document.styleSheets[0].cssRules[4].style.transitionDuration += ",1s";
    

    At this stage, both transitions will take effect.

    If you want to only have the original transition, you can either add it manually or simply...

    //Delete the Rule
    
    document.styleSheets[0].deleteRule(3);
    
    //Add the Original Rule Back Again
    
    document.styleSheets[0].insertRule(originalRule,3);
    

    If you do so, only the original transition (margin) will take effect, don't forget to also replace the originalHover rule to remove any other effects on hover.

    Note:

    For Chrome

    document.styleSheets[0].cssRules[3].style.webkitTransitionProperty
    

    For Firefox

    document.styleSheets[0].cssRules[3].style.mozTransitionProperty
    

    For IE insertRule and deleteRule do not work, there's these ones instead:

    addRule , removeRule
    

    LIVE DEMO FOR CHROME AND FIREFOX

    0 讨论(0)
提交回复
热议问题