javascript - 使用变换使一个元素出现在另一个元素的确切位置
问题描述
我有一个元素想要出现在另一个元素的确切位置。这个其他元素的比例和旋转发生了变化。第一个元素必须仅使用变换呈现另一个元素的外观。
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>
解决方案
推荐阅读
- informix - 如何在 Informix 中添加额外的假空列来选择结果?
- bigdata - 当公司使用开发/登台/生产环境进行软件开发时,如何调用登台表
- html - ASP.NET MVC 表行,包括来自模型的文本链接
- api - 如何在 Windows 机器上设置 Gravitee.io
- mongodb - MongoDB .msi 安装程序无法在 Windows 10 上运行
- jenkins - 詹金斯 - 矩阵作业 - 不同奴隶上的变量相互覆盖?
- android - 如何开启usb调试模式?
- php - 在 wordpress 数据库中添加带有数据的自定义行
- python - 在迭代文件夹结构时匹配文件中的文本
- python-2.7 - 使用python将一系列ppm图像转换为视频