用JavaScript和CSS实现“在页面中水平和垂直居中”的时钟
思路:实现起来最麻烦的事实上是水平居中和垂直居中,当中垂直居中是最麻烦的。
考虑到浏览器兼容性,网上看了一些资料,发如今页面中垂直居中确实没有什么太好的办法。
于是就採用了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>