代码描述:JavaScrip 浏览器 长宽自适应 元素垂直居中。JavaScrip兼容所有浏览器长宽自适应元素垂直水平居中
固定宽度的子元素垂直水平居中效果是非常的容易实现的,这里不多介绍了,具体可以参阅css实现div水平垂直居中代码一章节,如果不是固定的那就有点麻烦,当然在标准浏览器中是没问题, 但是如果要兼容所有浏览器就比较麻烦了,下面介绍一下使用js实现此功能的代码。 代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.51qianduan.com/" /> <title>51前端</title> <style type="text/css"> #box{ height:300px; width:300px; border:1px solid; position:relative; } #inner{ background-color:red; } </style> <script type="text/javascript"> window.onload=function(){ var box=document.getElementById("box"); var inner=document.getElementById("inner"); var w=inner.offsetWidth; var h=inner.offsetHeight; inner.style.position="absolute"; inner.style.left="50%"; inner.style.top="50%"; inner.style.marginLeft="-"+parseInt(w/2)+"px"; inner.style.marginTop="-"+parseInt(h/2)+"px"; } </script> </head> <body> <div id="box"> <span id="inner">内容自适应水平垂直居中</span> </div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能