我正在创建一个可平移和可缩放的 UI,它要求子对象在屏幕上居中,但我需要移动父对象以使子对象在屏幕上居中。
我的代码在 1 倍放大倍率下工作,但是当我应用 css3 转换来放大或缩小父级时,我的计算出错了。
如果您将父元素 css 变换和 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>
最佳答案
好吧,我通常不写 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
);
})
});
以下是我认为可能让您感到困难的事情(它们对我来说也是如此):
$("#child").position()
给出变换之后的位置,而$("#child").width ()
给出变换之前的宽度。也就是说,使用您发布的 CSS,但使用transform: matrix(2, 0, 0, 2, 0, 0);
然后使用$("#child").position()。左 == 460
但$("#child").width() == 150
。设置
$("#parent").css('left', ... )
时,它是变换之前的左偏移量,并且变换围绕中心缩放。也就是说,使用您发布的 CSS,但如果您想设置#parent
',则使用transform: matrix(1.5, 0, 0, 1.5, 0, 0);
'如果要将左边缘与窗口的左边缘对齐,那么您必须设置$("#parent").css('left', 175)
而不是$("# parent").css('left', 0)
正如我最初预期的那样。
关于javascript - 定位父元素以使其子元素在屏幕上居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35311183/