首页 > 解决方案 > 使用变换使一个元素出现在另一个元素的确切位置

问题描述

我有一个元素想要出现在另一个元素的确切位置。这个其他元素的比例和旋转发生了变化。第一个元素必须仅使用变换呈现另一个元素的外观。

在此处输入图像描述

const getRotation = el => {
  const st = window.getComputedStyle(el, null);
  const tr = st.getPropertyValue('transform');

  const values = tr.split('(')[1].split(')')[0].split(',');
  const a = values[0];
  const b = values[1];

  const angle = Math.round(Math.atan2(b, a) * (180/Math.PI));

  return angle;
}

const firstPhoto = document.querySelector('.first');
const secondPhoto = document.querySelector('.second');

const firstPhotoBox = firstPhoto.getBoundingClientRect();
const secondPhotoBox = secondPhoto.getBoundingClientRect();

const deltaX = secondPhotoBox.left - firstPhotoBox.left;
const deltaY = secondPhotoBox.top - firstPhotoBox.top;
const deltaW = secondPhotoBox.width / firstPhotoBox.width;
const deltaH = secondPhotoBox.height / firstPhotoBox.height;
const deltaR = getRotation(secondPhoto);

firstPhoto.style.transform = `translate(${deltaX}px, ${deltaY}px) scaleX(${deltaW}) scaleY(${deltaH}) rotateZ(${deltaR}deg)`;
div {
  opacity: 0.8;
}

.first {
  width: 200px;
  height: 100px;
  background: green;
}

.second {
  width: 260px;
  height: 400px;
  background: orange;
  transform: translate(20%, 5%) scale(0.8) rotateZ(-2deg);
}
<div class="first">Element 1</div>
<div class="second">Element 2</div>

标签: javascriptcssdom

解决方案


推荐阅读