javascript實現(xiàn)在指定元素中垂直水平居中
本章節(jié)介紹一下如何實現(xiàn)未知寬高的元素在指定元素下實現(xiàn)垂直水平居中效果,下面就以span元素為例子,介紹一下如何實現(xiàn)span元素在div中實現(xiàn)水平垂直居中效果,代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<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>
上面你的代碼實現(xiàn)了span元素在div中垂直水平居中效果,下面簡單介紹一下它的實現(xiàn)過程。
一.實現(xiàn)原理:
雖然css為明確給出span元素的尺寸,但是它畢竟有一個尺寸的,這個尺寸可以使用offsetWidth和offsetHeight屬性獲取,然后將此span元素設(shè)置為絕對定位,然后再將left和top屬性值分別設(shè)置為50%,但是這個時候并不是span元素的中心點垂直水平居中,而是span元素的左上角垂直水平居中,然后在設(shè)置span元素的負(fù)的外邊距,尺寸是span元素寬高的一半,這樣就實現(xiàn)了垂直水平居中效果。
例子二:
思路:實現(xiàn)起來最麻煩的其實是水平居中和垂直居中,其中垂直居中是最麻煩的??紤]到瀏覽器兼容性,網(wǎng)上看了一些資料,發(fā)現(xiàn)在頁面中垂直居中確實沒有什么太好的辦法。于是就采用了position:fixed屬性控制時鐘的絕對位置,通過clientWidth和clientHeight來獲取時鐘的寬和高,利用javascript控制marginLeft和marginTop來居中時鐘。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Centered Clock</title>
<style type="text/css">
body{
background: #fff;
}
body, div, p{
margin: 0;
padding: 0;
}
.center{
position: fixed;
left: 50%;
top: 50%;
}
.box{
border: 1px solid #000;
padding: 20px 30px;
font-size: 1.5em;
font-weight: 500;
margin: auto auto;
}
</style>
</head>
<body>
<div class="center">
<p class="box"></p>
</div>
</body>
<script type="text/javascript">
window.onload = function () {
getTimes();
var box = document.getElementsByClassName("box")[0];
box.style.marginLeft = -box.clientWidth / 2 + "px";
box.style.marginTop = -box.clientHeight / 2 + "px";
setInterval(getTimes, 1000);
}
function getTimes() {
var box = document.getElementsByClassName("box")[0];
var dateTime = new Date();
var year = dateTime.getFullYear();
var date = dateTime.getDate();
var month = dateTime.getMonth() + 1;
var hours = dateTime.getHours();
var minutes = dateTime.getMinutes();
var secondes = dateTime.getSeconds();
box.innerHTML = year + "-" + format(month) + "-" + format(date) + " " + format(hours) + ":"+ format(minutes) +":" + format(secondes);
}
function format(a) {
return a.toString().replace(/^(\d)$/, "0$1");
}
</script>
</html>
例子三:
思路:采用相對定位,設(shè)定left和top值為(pw-w)/2和(ph-h)/w,其中pw和ph為外部標(biāo)簽的寬與高,w和h為內(nèi)部標(biāo)簽的寬與高。
核心代碼:


以上就是給大家總結(jié)的三種javascript實現(xiàn)居中的例子,小伙伴們可以參考下,希望對大家能夠有所幫助。

