简体   繁体   English

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

[英]Align middle a div in another div (glitch)

在此输入图像描述

You can find jsFiddle demo here 你可以在这里找到jsFiddle演示

As you probably see on the picture I trying to align middle a circle (div, green) into another circle (div, grey). 正如你可能在图片上看到的那样,我试图将中间一个圆圈(div,绿色)对齐到另一个圆圈(div,灰色)。 I calculated the center of both div and made them equal, but the little green circle is still not in the middle. 我计算了两个div的中心并使它们相等,但是小绿圈仍然不在中间。

Where is the mistake? 哪里出错了? I just can't find it. 我找不到它。

The jquery I use to align circle (where o is the green circle, and $(this) is the grey one: 我用来对齐圆圈的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 });
};

Thank you in advance for any help! 预先感谢您的任何帮助!

Use jQuery UI's position method. 使用jQuery UI的position方法。 It allows you to position any element relative to any other element and abstracts all of the complications. 它允许您相对于任何其他元素定位任何元素并抽象所有复杂性。 (Courtesy of ogc-nick ). (由ogc-nick提供 )。

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

This might work better for you: HTML: 这可能对您更有效:HTML:

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

CSS: 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: JS:

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

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

The easiest method by far would've been to drop the JS and just use CSS pseudo elements (not supported in IE7 and below). 到目前为止最简单的方法是删除JS并使用CSS伪元素(IE7及以下版本不支持)。

http://jsfiddle.net/rzGX9/ 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM