在另一个div(毛刺)中间对齐一个div

时间:2013-05-20 19:18:39

标签: jquery html css

enter image description here

You can find jsFiddle demo here

正如你可能在图片上看到的那样,我试图将中间的圆圈(div,绿色)对齐到另一个圆圈(div,灰色)。我计算了两个div的中心并使它们相等,但是小绿圈仍然不在中间。

错误在哪里?我找不到它。

我用来对齐圆圈的jquery(其中o是绿色圆圈,$(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 });
};

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

使用jQuery UI的position方法。它允许您相对于任何其他元素定位任何元素并抽象所有复杂性。 (由ogc-nick提供)。

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

答案 1 :(得分: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/

答案 2 :(得分: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; }