我有2个元素,我将其中一个放置在另一个元素的offsetLeft和offsetTop上。当不旋转时,它们的位置很好,但是当旋转时,它们会相对于彼此失去位置,因为它们绕其中心旋转。有没有办法解决这个问题,如果有一些公式,您也可以解释一下吗? 示例:http://jsfiddle.net/9t6n8dmk/8/
//firstExample without rotation
<div class ="first-element" id="first-element">
</div>
<div class="second-element" id="second-element">
</div>
//secondExample with rotation
<div class ="first-element-rotation" id="first-element-rotation">
</div>
<div class="second-element-rotation" id="second-element-rotation">
</div>
let firstElement = document.getElementById("first-element");
let secondElement = document.getElementById("second-element");
secondElement.style.top = firstElement.offsetTop + "px";
secondElement.style.left = firstElement.offsetLeft + "px";
let firstElementRotation = document.getElementById("first-element-rotation");
let secondElementRotation = document.getElementById("second-element-rotation");
secondElementRotation.style.top = firstElementRotation.offsetTop + "px";
secondElementRotation.style.left = firstElementRotation.offsetLeft + "px";
.first-element{
background-color: black;
height: 50px;
width: 150px;
}
.second-element{
background-color: red;
height: 50px;
width: 50px;
position:absolute;
}
.first-element-rotation{
background-color: black;
height: 50px;
width: 150px;
margin-top:100px;
transform: rotate(30deg);
}
.second-element-rotation{
background-color: red;
height: 50px;
width: 50px;
position:absolute;
transform: rotate(30deg);
}
答案 0 :(得分:2)
设置transform-origin
属性会有所帮助:
let firstElement = document.getElementById("first-element");
let secondElement = document.getElementById("second-element");
secondElement.style.top = firstElement.offsetTop + "px";
secondElement.style.left = firstElement.offsetLeft + "px";
let firstElementRotation = document.getElementById("first-element-rotation");
let secondElementRotation = document.getElementById("second-element-rotation");
secondElementRotation.style.top = firstElementRotation.offsetTop + "px";
secondElementRotation.style.left = firstElementRotation.offsetLeft + "px";
.first-element {
background-color: black;
height: 50px;
width: 150px;
}
.second-element {
background-color: red;
height: 50px;
width: 50px;
position: absolute;
}
.first-element-rotation {
background-color: black;
height: 50px;
width: 150px;
margin-top: 100px;
transform-origin: 0 100%;
transform: rotate(30deg);
}
.second-element-rotation {
background-color: red;
height: 50px;
width: 50px;
position: absolute;
transform-origin: 0 100%;
transform: rotate(30deg);
}
//firstExample without rotation
<div class="first-element" id="first-element">
</div>
<div class="second-element" id="second-element">
</div>
//secondExample with rotation
<div class="first-element-rotation" id="first-element-rotation">
</div>
<div class="second-element-rotation" id="second-element-rotation">
</div>
答案 1 :(得分:0)
一种解决方案可能是将2个对象与<div>
元素组合在一起,然后旋转该元素。