我正在使用扩展缩放元素

 transform: scale(1.2);


现在,我需要获得悬停时的顶部和左侧位置,但这会给我缩放位置的顶部和左侧。。有道理,但是我想要正常状态的顶部和左侧吗?有一个简单的方法来做到这一点吗?

最佳答案

根据transform-origin和元素的对齐方式,可以通过将宽度和高度乘以scaleX和scaleY的乘数来计算附加偏移。

例:

var element = $("#myDiv");
var prefixes = ["-moz-", "-webkit-", "-o-", "-ms-", ""];
var transX = 1, transY = 1, originX = .5, originY = .5, match;
for(var i=0; i<prefixes.length; i++){
    var prefix = prefixes[i];
    var transform = element.css(prefix+"transform");
    if(!transform) continue;
    match = transform.match(/scale\((\d+),(\d+)\)/i);
    if(match){
        transX = match[1];
        transY = match[2];
    } else if(match = transform.match(/scale\((\d+)\)/i)){
        transX = transY = match[1];
    } else if(match = transform.match(/scale[XY]\(\d+\)/i)){
        transX = transform.match(/scaleX\((\d+)\)/i);
        transX = transX ? transX[1] : 1;
        transY = transform.match(/scaleY\((\d+)\)/i);
        transY = transY ? transY[1] : 1;
    }
    var origin = element.css(prefix+"tranform-origin").match(/(\d+)% (\d+)%/); /*Default: 50% 50%*/
    if(origin){
        originX = origin[1]/100;
        originY = origin[2]/100;
    } else {
        //Investigate yourself. What would be the value if it doesn't exist?
    }
}

if(match){ /*A match has been found, thus transX and transY are defined*/
    /*Width * originX * scaleY =
        width * [relative affected part of element] * [scale factor]
        = adjusted offset*/
    var minusLeft = element.width() * originX * scaleX;
    var minusTop = element.height() * originY * scaleY;
    /*Do something, for example:*/
    element.css("left", "-="+minusLeft+"px");
    element.css("top", "-="+minusTop+"px");
}

10-08 18:17