欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

純js代碼實(shí)現(xiàn)未知寬高的元素在指定元素中垂直水平居中顯示

 更新時(shí)間:2015年09月12日 16:41:51   作者:愚蠢的神  
本章節(jié)介紹一下如何實(shí)現(xiàn)未知寬高的元素在指定元素下實(shí)現(xiàn)垂直水平居中效果,代碼簡單易懂,需要的朋友可以參考下本文

下文以span元素為例子,介紹一下如何實(shí)現(xiàn)span元素在div中實(shí)現(xiàn)水平垂直居中效果,代碼如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>腳本之家</title>
<style type="text/css">
#box{
 width:200px;
 height:150px;
 background:blue;
 position:relative;
}
#antzone{
 background:green;
}
</style>
<script type="text/javascript">
window.onload=function(){
 var obox=document.getElementById("box");
 var oantzone=document.getElementById("antzone");
 var w=oantzone.offsetWidth;
 var h=oantzone.offsetHeight;
 oantzone.style.position="absolute";
 oantzone.style.left="50%";
 oantzone.style.top="50%";
 
 oantzone.style.marginLeft=-(w/2)+"px";
 oantzone.style.marginTop=-(h/2)+"px";
}
</script>
</head>
<body>
<div id="box">
 <spanj id="antzone">腳本之家</span>
</div>
</body>
</html>

上面你的代碼實(shí)現(xiàn)了span元素在div中垂直水平居中效果,下面簡單介紹一下它的實(shí)現(xiàn)過程。

一.實(shí)現(xiàn)原理:

雖然css為明確給出span元素的尺寸,但是它畢竟有一個(gè)尺寸的,這個(gè)尺寸可以使用offsetWidth和offsetHeight屬性獲取,然后將此span元素設(shè)置為絕對定位,然后再將left和top屬性值分別設(shè)置為50%,但是這個(gè)時(shí)候并不是span元素的中心點(diǎn)垂直水平居中,而是span元素的左上角垂直水平居中,然后在設(shè)置span元素的負(fù)的外邊距,尺寸是span元素寬高的一半,這樣就實(shí)現(xiàn)了垂直水平居中效果。

以上就是本文的全部內(nèi)容,今天就到此為止,后續(xù)給大家更新scrollTop、offsetHeight和offsetTop等屬性用法詳解,請持續(xù)關(guān)注本站,謝謝。

相關(guān)文章

最新評論