【发布时间】:2016-02-11 00:11:54
【问题描述】:
我正在创建一个可平移和可缩放的 UI,它要求子对象在屏幕上居中,但是我需要移动父对象以使子对象在屏幕上居中。
我的代码在 1 倍放大倍率下工作,但是当我应用 css3 变换来放大或缩小父级时,我的计算出错了。
如果将父元素 css transform 和 js mult var 的第 1 个和第 4 个元素更改为 0.5 或 2,则计算结束。
任何帮助将不胜感激,因为我已经为此烦恼了几天。
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