Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - Add a transform value to the current transforms that are already on the element?

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

<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 transforms, but applying it via element.style.webkitTransform = "rotateX(20deg)" loses the other values.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use the += operator to append the rotateX(20deg) to the already existing transformation.

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

Note: I have used a different transformation in the below snippet for the visual effect but 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...