2011-10-21 30 views
3

我允许用户使用jQuery旋转来旋转图像。但是,当他们这样做时,图像会在包含div的外部流动,并与控件重叠。如何使用jQuery获取图像的中心坐标?

我的想法是,如果我可以得到图像中心的坐标,然后我可以计算它旋转的最大半径,并使用该值使用$ .animate调整包含div的大小。

我该如何解决这个在jQuery中?

+2

你想以图像的中心作为相对坐标还是绝对的? – Mikhail

+1

“高度/ 2”和“宽度/ 2”有什么问题? – Rob

回答

2

可以通过使用图像尺寸计算的中心时,其加载:

var img = $("#image"), 
    loaded = false; 

img.load(function(){ 
    if (loaded) return; 
    loaded = true; 
    var cx = this.width/2, 
     cy = this.height/2; 
    //If you want center coordinates relative to the document 
    var pos = $(this).offset(); 
    cx += pos.left; 
    cy += pos.top; 
}); 

//Trigger the event if the image is already loaded 
if(img[0].complete) { 
    img.trigger("load"); 
} 
1

可以使用offsetposition到那里的位置再加入宽度/ 2和高度/ 2到这样这些数字:

var location = $('img.selector').offset(); 
var center = new Object(); 
center.x = location.left + ($('img.selector').width()/2); 
center.y = location.top + ($('img.selector').height()/2); 

如果图像具有某种类型的填充或边框,则可能需要使用outHeight()和outerWidth()来代替width()和height()。

我希望这有助于!