Add conversion value to current conversions that are already in the element?

Let's say I have a div that dynamically added translateX and translateY values.

 <div class="object child0" style="-webkit-transform: translateX(873.5px) translateY(256px); width: 50px; height: 50px;"> 

I want to add rotateY(20deg) to the current transformations, but applying it through element.style.webkitTransform = "rotateX(20deg)" loses other values.

Is there a way to add rotateY without losing the translateX and translateY conversions?

+3
source share
1 answer

You can use the += operator to add rotateX(20deg) to an existing transformation.

 el.style.webkitTransform += "rotateX(20deg)"; 

Note. I used a different transformation in the snippet below for a visual effect, but the method is the same.

 window.onload = function() { var el = document.getElementsByTagName("div")[0]; el.style.webkitTransform += "rotateZ(20deg)"; console.log(el.style.webkitTransform); document.getElementById("changeDeg").onclick = changeDeg; //event handler } function changeDeg() { var el = document.getElementsByTagName("div")[0]; var re = /(rotateZ)(\(.*(?:deg\)))/g; //regex to match rotateZ(...deg) var newDeg = 40; if (el.style.webkitTransform.match(re).length != -1) { el.style.webkitTransform = el.style.webkitTransform.replace(re, '$1(' + newDeg + 'deg)'); // $1 is first capturing group which is "rotateZ" } console.log(el.style.webkitTransform); } 
 div { background: red; margin-bottom: 20px; } 
 <div class="display-object child0" style="-webkit-transform: translateX(43.5px) translateY(6px); width: 50px; height: 50px;"></div> <button id="changeDeg">Change Rotation</button> 
+5
source

All Articles