javascript - 如何计算居中 div 的顶部和左侧位置?
问题描述
这个问题比标题复杂一点,我试图获取使用这些 css 属性的居中 div 的顶部和左侧值:
top:50%;
left:50%;
transform:translate(-50%, -50%);
我能够毫无问题地获得顶部和左侧的值,但我不明白translate(-50%, -50%)
下面论坛的行为方式。
尝试 Fiddle 进行测试:https ://jsfiddle.net/nqym3s4b/
...
<div id="div1">
<div id="div2">...</div>
</div>
var div = document.querySelector('#div2');
var w = div.offsetWidth,
h = div.offsetHeight;
// top & left
var lw = (w / 100) * 50,
lh = (h / 100) * 50;
// top & left with transform(-50%, -50%)
var tw = (lw / 100) * 50,
th = (lh / 100) * 50;
left = 'left: ' + tw + 'px;';
top = 'top: ' + th + 'px;';
有任何想法吗?
解决方案
translate
将考虑内部width
元素的/ height
,因此 50% 是已翻译元素的宽度/高度的一半,而/将考虑父元素的尺寸。top
left
计算是两个值的简单相加(我添加了第三个 div#div2
以便您可以看到结果)
var div1 = document.querySelector('#div1'); //parent element
var div2 = document.querySelector('#div2'); //translated element
var w1 = div1.offsetWidth,
h1 = div1.offsetHeight;
var w2 = div2.offsetWidth,
h2 = div2.offsetHeight;
var lw = (w1 / 100) * 50 + (-w2 / 100) * 50,
lh = (h1 / 100) * 50 + (-h2 / 100) * 50;
document.querySelector('#left').innerHTML = 'left: ' + lw + 'px;';
document.querySelector('#top').innerHTML = 'top: ' + lh + 'px;';
document.querySelector('#div3').style.left = lw + 'px';
document.querySelector('#div3').style.top = lh + 'px';
#div1 {
width: 560px;
height: 240px;
background: red;
position: relative;
}
#div1 #div2 {
width: 340px;
height: 120px;
background: yellow;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#div1 #div3 {
width: 50px;
height: 50px;
background: blue;
position: absolute;
opacity: 0.2;
}
<div id="div1">
<div id="div2">
<span id="left"></span>
<br>
<span id="top"></span>
</div>
<div id="div3">
<!-- to compare -->
</div>
</div>
推荐阅读
- angular - 角度材料表排序 - 在 *ngIf 条件内时数据不排序
- windows - netsh winhttp 似乎不起作用。任何建议为什么?
- c - 来自比参数中指定的更多进程的输出
- excel - 根据一组单元格隐藏另一张纸上的行,然后打印
- powershell - 从嵌套的 zip 文件中提取特定文件
- javascript - 如何在 VueJS 中获得多个 td 选择
- javascript - Angular material Stepper中每个步骤的浏览器后退和前进按钮
- anaconda - 未加载库:@rpath/libpython3.5m.dylib --> Jupyter Notebook 内核未启动
- css - 任何普通和粗体的通用非衬线字体
- input - 自动热键的按住功能