CSS从中心翻译回来

CSS Translate back from center?

本文关键字:翻译 回来 CSS      更新时间:2023-09-26

所以我写了一些代码来将我的盒子从窗口上的某个位置转换到中心,我有原始位置,例如:原始盒子

{
    top: 52.16538619995117, 
    right: 685.6694946289062, 
    bottom: 214.66795349121094, 
    left: 523.1669311523438, 
    width: 150
}

原框的宽度/高度为150px,当它被移动到中心时,它变成了300px。一些基本代码通过以下方式将其重新定位到中心:

top = window.innerHeight / 2 - currentPosition.top - 150 /2 
left = window.innerWidth / 2 - currentPosition.left - 150 /2 

现在假设组件的新坐标为:集中箱

{
    top: 74.78038787841797, 
    right: 928.7755126953125, 
    bottom: 374.7803955078125, 
    left: 628.7755126953125, 
    width: 300
}

我用:

把它重新定位到中间很费时间
transform: "translate(xTarget, yTarget)";

这应该比我想象的要容易得多,但由于某种原因,它总是与原来的不同。

下面是我写的一个函数来帮助确定平移坐标:

getCoordinateTarget(target, offset, currentNotePosition) {
        const xDifference = target.left - currentNotePosition.left;
        const yDifference = target.top - currentNotePosition.top;
        const xTarget = xDifference > 0 ? xDifference - offset.x : -Math.abs(xDifference) - offset.x;
        const yTarget = yDifference > 0 ? yDifference - offset.y : -Math.abs(yDifference) - offset.y;
        return {
            y: yTarget,
            x: xTarget
        };
    }

我对CSS转换的工作方式有一个很大的误解。所以我最初用平移来移动它,我所要做的就是将转换设置为空,然后组件将被重新定位回原始位置。

字面意思transform: "";