【问题标题】:Positioning a parent element to center it's child on the screen定位父元素以使其子元素在屏幕上居中
【发布时间】:2016-02-11 00:11:54
【问题描述】:

我正在创建一个可平移和可缩放的 UI,它要求子对象在屏幕上居中,但是我需要移动父对象以使子对象在屏幕上居中。

我的代码在 1 倍放大倍率下工作,但是当我应用 css3 变换来放大或缩小父级时,我的计算出错了。

如果将父元素 css transform 和 js mult var 的第 1 个和第 4 个元素更改为 0.5 或 2,则计算结束。

任何帮助将不胜感激,因为我已经为此烦恼了几天。

JS fiddle

Javascript

$(function() {

$("#child").click(function(e) {

var mult = 1

$("#parent").css('left',
  (($(window).width() - $("#parent").width()) / 2) +
  ($("#parent").width() * mult) / 2 -
  ($("#child").position().left / mult) -
  ($("#child").width() * mult) / 2
);

$("#parent").css('top',
  (($(window).height() - $("#parent").height()) / 2) +
  ($("#parent").height() * mult) / 2 -
  ($("#child").position().top / mult) -
  ($("#child").height() * mult) / 2
);

})

});

CSS

.parent {
  position: relative;
}

#child {
  border: 1px solid red;
  position: absolute;
  z-index: 3;
  width: 150px;
  height: 150px;
  top: 300px;
  left: 230px;
  background-color: cornflowerblue;
  color: white
}

#parent {
  position: relative;
  width: 700px;
  height: 900px;
  transform: matrix(1, 0, 0, 1, 0, 0);
  border: 1px solid red;
  background: pink
}

HTML

<div class="parent">
  <div id="parent">
    <div class="testBox" id="child">CLICK ME</div>
  </div>
</div>

【问题讨论】:

    标签: javascript jquery css math css-position


    【解决方案1】:

    好的,我通常不写 JS,但我已经成功了:

    $(function() {
    
      $("#child").click(function(e) {
    
        var mult = 3
    
        $("#parent").css('left',
            (($(window).width()-$("#child").width()*mult) / 2) -
            $("#child").position().left +
            (mult-1) * $("#parent").width() / 2
        );
    
        $("#parent").css('top',
            (($(window).height()-$("#child").height()*mult) / 2) -
            $("#child").position().top +
            (mult-1) * $("#parent").height() / 2
        );
      })
    });
    

    以下是我认为可能让您感到困难的事情(他们为我做了):

    1. $("#child").position() 给出变换之后的位置,而$("#child").width() 给出变换之前的宽度。也就是说,使用您发布的 CSS,但使用 transform: matrix(2, 0, 0, 2, 0, 0);,然后使用 $("#child").position().left == 460,但使用 $("#child").width() == 150

    2. 当设置$("#parent").css('left', ... ) 时,它是变换前的左偏移,并且变换围绕中心缩放。也就是说,使用您发布的 CSS 但使用 transform: matrix(1.5, 0, 0, 1.5, 0, 0); 如果您想将 #parent 的左边缘设置为与窗口的左边缘对齐,那么您必须将 $("#parent").css('left', 175) 而不是 $("#parent").css('left', 0) 设置为我最初是预料到的。

    【讨论】:

    • 非常感谢@psuedoDust,它运行良好。您对变换 after 和变换前 width 的位置值的描述是有道理的。我对 (mult-1) 部分的工作原理有些困惑。我认为它与小于 1 的变换值有关?
    • (mult-1) 的事情与 left 在变换之前设置的事实有关,变换会将 #parent by(mult-1) * $("#parent").width() / 2 的“真实”左侧位置向左移动,因为它围绕中心缩放。你设置的左边是远离中心的$("#parent").width() / 2,“真正的”左边(缩放后)是mult * $("#parent").width() / 2,减去两者,你就得到了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多