【问题标题】:JQuery set an element at the middle of anotherJQuery 将一个元素设置在另一个元素的中间
【发布时间】:2012-01-29 21:48:36
【问题描述】:

您好,我有一些类似的元素:

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

以及相应数量的元素(没有任何父元素,它们就在body标签之后)具有:

position: absolute;

还有这样的 id:

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

现在我想将第二组元素准确地放置在引用元素的中间(垂直和水平),我该怎么做?

我已经尝试过偏移:

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

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

但它只为顶部和左侧设置位置,将助手定位在元素的左上角而不是其中心

【问题讨论】:

  • 您不仅要根据元素的位置,还要根据元素和助手的宽度和高度来计算助手的位置。 (类似于 helper.top = elmt.top + (elmt.height - helper.height)/2)

标签: javascript jquery css position positioning


【解决方案1】:
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;
}

拨打$("#helper-one").center($("#one"));

ps:你甚至可以通过解析原始元素的 id 来跳过 obj 参数

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();       
});

【讨论】:

  • 有一些错误,这对我有用 this.css("top",(loc.top + obj.outerHeight() / 2 - this.outerHeight() / 2 + 'px') ); this.css("left",(loc.left + obj.outerWidth() / 2 - this.outerWidth() / 2 + 'px'));
  • @Matteo Pagliazzi 我检查了脚本 - 它运行没有任何问题。 this works for me你写了同样的东西,只是打开了括号。
  • @Matteo Pagliazzi 抱歉,我已经在方形 div 上测试过了 :))
猜你喜欢
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多