在Javascript中旋转图像时出现奇怪的定位问题

weird positioning problem while rotating image in Javascript

本文关键字:定位 问题 Javascript 旋转 图像      更新时间:2023-09-26

我遇到了一个奇怪的定位问题,而旋转图像包装到JavaScript中的div。当图像旋转90°或270°时,图像突然位于其父div上方50px,右侧50px。如果旋转0°或180°,则没有问题。

这就是我正在做的:

<html>
<head>
    <script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
</head>
<body>
    <div id="crop_container" style="width:400px; height:400px; border:solid 1px;">
        <img src="http://a8.sphotos.ak.fbcdn.net/hphotos-ak-snc6/249740_10150195623627623_506197622_7383520_7286937_n.jpg" style="display:block; position:relative; width:400px; height:400px;" />
    </div>
    <script language="JavaScript">
    var $cropContainer =  $("#crop_container");
    var $cropImage =  $("#crop_container img");
    var degrees = 90;
    $cropImage.css({"width":400, "height":300});
    $cropContainer.css({"width":300, "height":400});
    $cropImage.css({"-webkit-transform":"rotate("+degrees+"deg)","-moz-transform":"rotate("+degrees+"deg)"});
    //$cropImage.css({"top":50, "right":50});
    </script>
</body>
</html>

现在,当你取消最后一个css调整行,从顶部和右侧校正50px,它工作得很好,但我不知道为什么会发生这种情况?

任何建议将不胜感激!

谢谢!乔妮

这取决于您希望它做什么。它是围绕图像的中点旋转,而不是矩形。

  • 中点占位符:(150, 200)
  • 中点图像:(200, 150) .

确实存在50px差异。您可以通过翻译

来改变旋转之前旋转的中点:
translate(-50px, 50px) rotate("+degrees+"deg)

使图像中点变为(200 - 50, 150 + 50),即(150, 200),这是您想要的。

http://jsfiddle.net/4UUJN/2/

当你将一个风景图像旋转90度变成一个肖像图像时,它会保持在它的原始位置的中心。由于宽度和高度相差100像素,变换将差异分配到顶部和底部,这就是您的50像素的来源。