2013-05-20 57 views
7

enter image description here中間對齊在另一個DIV(故障)一個div

You can find jsFiddle demo here

正如你可能看到的畫面我試圖對準中間的圓圈(DIV,綠色)到另一個圈子(DIV,灰色) 。我計算了兩個div的中心並使它們相等,但小綠圈仍然不在中間。

哪裏錯了嗎?我無法找到它。

我用它來對準圈(其中o是綠色圓圈的jQuery和$(this)是灰色的:

$.fn.center = function(o) { 
    var _X = parseInt(o.css('left')) + parseInt(o.width())/2 - parseInt($(this).width())/2; 
    var _Y = parseInt(o.css('top')) + parseInt(o.height())/2 - parseInt($(this).height())/2; 
    $(this).offset({ top: _Y, left: _X }); 
}; 

預先感謝您的任何幫助

+2

我建議使用jQuery UI的[position](http://jqueryui.com/position/)方法。它可以讓你定位任何元素相對於任何其他元素,並抽象出所有的複雜情況。 –

+0

謝謝你的快速答覆,這個問題解決了:) – Pho3nixHun

+0

+1的解決方案添加到 –

回答

1

使用jQuery UI的position方法!它允許你定位任何相對於任何其他元素的元素,並提取所有的併發症(由ogc-nick提供)

$.fn.center = function(o) { 
    $(this).position({ 
     my: "center middle", 
     at: "center middle", 
     of: o 
    }); 
}; 
0

到目前爲止,最簡單的方法就是放棄JS,並使用CSS僞元素(IE7及以下版本不支持)。

http://jsfiddle.net/rzGX9/

.small-circle { position: relative; width: 20px; height: 20px; border-radius: 20px; background: #f00; } 
.small-circle:after { z-index: -1; content:""; position: absolute; background: #00f; border-radius: 50px; width: 50px; height: 50px; left: 50%; top: 50%; margin: -25px 0 0 -25px; display: none;} 
.small-circle:hover:after { display: block; } 
1

這可能會更好地爲您: HTML:

<div id="range_sword"> 
    <div class="jk"></div> 
    </div> 

CSS:

.range_sword, body, div{ 
    padding:0px; 
    margin:0px; 
} 

.jk{ 
    display: block; 
    min-width: 20px; 
    min-height: 20px; 
    border-radius: 10px; 
    background-color: green; 
} 

#range_sword{ 
    background-color: transparent; 
    border-radius: 100px; 
    position: absolute; 
    border-style: dashed; 
    border-color: transparent; 
    border-width:2px; 
    padding:15px; 
} 
#range_sword:hover{ 
    background-color:#cdcdcd; 
    border-color: #adadad; 
} 

JS:

$("#range_sword").draggable(); 

jsfiddle:http://jsfiddle.net/H8Tsc/2/