Stack CSS Transitions using multiple classes without overriding

流过昼夜 提交于 2019-12-01 14:12:38

问题


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

.container { transition: margin .2s; }
.container.t-padding { transition: padding .2s; }

The problem: Property is overridden rather than stacking

http://jsfiddle.net/yz2J8/2/ (The problem)

My temporary solution: Add the previous transition to the rule

.container { transition: margin .2s; }
.container.t-padding { transition: padding .2s, margin .2s; }

http://jsfiddle.net/ZfQcp/6/ (My temporary solution)

What's a better solution??

How can I avoid having to create tons of rules to combine these?


回答1:


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



来源:https://stackoverflow.com/questions/16888312/stack-css-transitions-using-multiple-classes-without-overriding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!