简体   繁体   中英

JQuery set an element at the middle of another

Hi I have some elements like these:

<div id="one">content</div>
<div id="two">content</div>

and a corrispondent number of elements (without any parent, they are just after the body tag) that have:

position: absolute;

and with an id like that:

id="helper-one" refers to id="one"

Now i want to place the second group of elements exactly at the middle (vertical and horizontal) of referred elements, how can i do that?

I've tried with offset:

    var one_offset = $("#one").offset();

    $("#helper-one").offset({ top: one_offset.top, right: one_offset.right, left:one_offset.left, bottom: one_offset.bottom})

but it set position only for top and left positionating the helper at the top-left corner of the element and not at its center

jQuery.fn.center = function (obj) {
  var loc = obj.offset();
  this.css("top",(obj.outerHeight() - this.outerHeight()) / 2 + loc.top + 'px');
  this.css("left",(obj.outerWidth() - this.outerWidth())  / 2 + loc.left+ 'px');
  return this;
}

Call as $("#helper-one").center($("#one"));

ps: you may even skip obj argument by parsing the id of the original element

jQuery.fn.center = function () {
  var obj = $('#' + this.attr('id').split('-')[1]), loc = obj.offset();
  this.css("top",(obj.outerHeight() - this.outerHeight()) / 2 + loc.top + 'px');
  this.css("left",(obj.outerWidth() - this.outerWidth())  / 2 + loc.left+ 'px');
  return this;
}

$(document).ready(function(){
   $("#helper-one").center();       
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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