這個小範例用一個圓形外框、一根細長指針和一個圓點,模擬真實時鐘的秒針走動。核心只有兩件事:先用 jQuery 把元素擺到正確位置,再用 CSS transform: rotate() 定時更新角度。
外框 .framehovertree 用 border-radius:50% 變成圓形並設為 position:relative,作為子元素的定位基準。指針 .centerhovertree 高 200 像素、寬 4 像素,靠 transform-origin: 50% 100% 把旋轉中心固定在「底部中點」,如此旋轉時才像真正的指針。中央的圓點 .smallhovertree 則用圓角做出樞紐的視覺效果。
置中不能寫死像素,而應依容器實際尺寸推算:
$(function () {
var centerDiv = $(".centerhovertree"), frameDiv = $(".framehovertree");
// 指針:水平置中,垂直方向讓底端落在圓心
$(".centerhovertree").css({
"left": (frameDiv.width() - centerDiv.width()) / 2,
"top": (frameDiv.height() / 2 - centerDiv.height())
});
// 圓點:完全置中
var smallhovertree = $(".smallhovertree");
$(".smallhovertree").css({
"left": (frameDiv.width() - smallhovertree.width()) / 2,
"top": (frameDiv.height() - smallhovertree.height()) / 2
});
});
秒針每走一格是 6 度(360 除以 60),所以只要把目前的秒數乘以 6 就是目標角度:
function clock() {
document.querySelector(".centerhovertree").style.transform =
"rotate(" + (new Date().getSeconds() * 6) + "deg)";
}
var int = self.setInterval("clock()", 50);
這裡用 50 毫秒的間隔而非 1000 毫秒,是為了讓指針在跨秒瞬間就能立即更新,視覺上不拖泥帶水。若想加入分針與時針,只要再準備兩個元素,分別換算 分鐘 × 6 與 (小時 % 12 + 分鐘 / 60)× 30 即可。
<!DOCTYPE html>
<html>
<head>
<style>
.framehovertree {
position: relative;
height: 410px;
width: 410px;
margin: 100px;
border: 1px solid black;
border-radius:50%;
}
.centerhovertree {
height:200px;
width:4px;
position: absolute;
border: 0px solid black;
background-color: yellow;
transform: rotate(90deg);
transform-origin: 50% 100%;
border-radius:2px;
z-index:99999
}
.smallhovertree {
width: 10px;
height: 10px;
background-color: hotpink;
position: absolute;
border-radius: 50%;
z-index: 999;
}
</style>
<script src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="div1" class="framehovertree"><div class="smallhovertree"></div>
<div id="div2" class="centerhovertree"></div>
</div>
<script>
$(function () {
var centerDiv = $(".centerhovertree"), frameDiv = $(".framehovertree")
$(".centerhovertree").css({ "left": (frameDiv.width() - centerDiv.width()) / 2, "top": (frameDiv.height() / 2 - centerDiv.height()) })
var smallhovertree = $(".smallhovertree")
$(".smallhovertree").css({ "left": (frameDiv.width() - smallhovertree.width()) / 2, "top": (frameDiv.height() - smallhovertree.height()) / 2 })
})
function clock() {
document.querySelector(".centerhovertree").style.transform = "rotate(" + ((new Date().getSeconds()) * 6) + "deg)";
}
var int = self.setInterval("clock()", 50)
</script>
</body>
</html>