问题
I got a container with unknown nested elements and I would like to move a selected child target around using js + transform translation. The problem I have is that a parent element can be scaled so the selected target moves faster/slower depending on the scale. And rotation makes it also harder to move it in the direction of the mouse movement.
How should I go about solving this problem? My assumption is that I need to walk up the DOM tree and combine all the matrixes and add, subtract values to figure out how much something needs to be moved. Eventually I need to also fix rotation support but i will deal with that later and maybe in another question.
But for now i have run into an error:
Error: Out of skills
at <brain>:1:∞
const target = document.querySelector('.target')
let init = null // Stores drag start event
target.onmousedown = evt => {
evt.preventDefault()
init = evt
}
// clear init event
onmouseup = () => init = null
// move the target around
onmousemove = evt => {
if (init) {
const x = evt.clientX - init.clientX
const y = evt.clientY - init.clientY
target.style.transform = `translate(${x}px, ${y}px)`
}
}
.nested {
position: absolute;
border: 4px solid #ccc;
width: 100px;
height: 100px;
top: 50px;
left: 70px;
/* box-sizing: border-box; */
}
.nested.rotate {
transform-origin: 0 0;
transform: rotate(-30deg);
}
.nested.scale {
transform: scale(1.5, 1.5);
}
.nested .target {
top: 50px;
left: 50px
}
html, body {
position: relative;
height: 100%;
margin: 0;
padding: 0;
}
.description {
padding: 10px;
}
.target {
position: absolute;
width: 100px;
height: 100px;
top: 150px;
left: 100px;
line-height: 100px;
text-align: center;
background: #ee8;
color: #333;
font-weight: bold;
border: 1px solid #333;
box-sizing: border-box;
transform: translate(18px, -70px);
}
<div class="container">
<div class="nested first">
No Transform
<div class="nested scale">
scale(1.2, 1.2)
<div class="nested rotate">
rotate(30deg)
<div class="target">Target</div>
</div>
</div>
</div>
</div>
bug issue: If you drag an element (x,y) inside a parent that has been previously rotated, then this.x and this.y values inside the onMove callback refer to horizontal and vertical directions, ignoring the fact that the parent is rotated. The result is that if, for example, you rotate the parent by 90deg, when you drag the child horizontally it moves vertically and viceversa.
来源:https://stackoverflow.com/questions/64169261/moving-element-with-n-nested-transform