3 javascript dom vertical-alignment
我正试图用Javascript垂直居中一个div.因为文本会发生变化,所以我不能使用固定的高度.
我想在没有 Jquery的情况下这样做.
#box2 {
width: 100%;
height: 100%;
position:relative;
background-color: orange;
}
#informationBox {
padding: 0.5em;
background-color: #fff;
border-radius: 12pt;
border: solid black 3pt;
max-width: 683px;
margin: 0 auto;
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
var container = document.getElementById("#box2");
var inner = document.getElementById("#informationBox");
var inHeight = inner.offsetHeight;
container.style.height=(window.innerHeight);
container.style.width=window.innerWidth;
var conHeight=container.offsetHeight;
inner.style.marginTop=((conHeight-inHeight)/2);
Run Code Online (Sandbox Code Playgroud)
任何帮助都会很棒:)
你几乎拥有它,你只需要改变几件事.首先,getElementById只需要一个id-string,而不是一个选择器.其次,您需要在样式分离中添加"px".
var container = document.getElementById("box2");
var inner = document.getElementById("informationBox");
var inHeight = inner.offsetHeight;
container.style.height = window.innerHeight;
container.style.width = window.innerWidth;
var conHeight = container.offsetHeight;
inner.style.marginTop = ((conHeight-inHeight)/2)+'px';
Run Code Online (Sandbox Code Playgroud)
这是一个更新的小提琴:http://jsfiddle.net/EttZQ/1/
| 归档时间: |
|
| 查看次数: |
16465 次 |
| 最近记录: |