DIV CSS 佈局教程網

jQuery 與純 CSS3 兩種同心圓画法對照
編輯:JQuery特效代碼     

效果預覽:https://hovertree.com/texiao/jquery/24/

CSS3 畫圓的基礎技巧:https://hovertree.com/h/bjae/css3circle.htm

同心圓的原理其實很單純:外層一個圓形容器設定 position:relative,內層小圓用絕對定位擺放,再設法讓它置中。置中的做法有兩條路——用 jQuery 計算座標,或純靠 CSS 完成,本文兩種都示範。

做法一:用 jQuery 計算置中位置

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>jQuery畫同心圓 - 何問起</title><meta name="viewport" content="width=device-width, initial-scale=1" />
 <meta charset="utf-8" />
 <style>
 .framehovertree {
 position: relative;
 margin: 100px auto;
 width: 300px;
 height: 300px;
 border-radius: 150px;
 border: 1px solid green;
 background-color:greenyellow
 }
 .centerhovertree {
 width: 150px;
 height: 150px;
 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 class="framehovertree">
 <div class="centerhovertree"></div>
 </div>
 <script>
 $(function () {
 var centerDiv = $(".centerhovertree"), frameDiv = $(".framehovertree")
 $(".centerhovertree").css({ "left": (frameDiv.width() - centerDiv.width()) / 2, "top": (frameDiv.height() - centerDiv.height()) / 2 })
 })
 </script>
</body>
</html>

關鍵那行程式碼是「容器寬度減去小圓寬度再除以二」,水平和垂直各算一次,小圓就精準落在正中央。這種做法的優點是尺寸可以隨時用 JavaScript 動態改變。

做法二:純 CSS3 實現,不需要 JavaScript

其實只要同時設定 margin:auto 與四邊 0,絕對定位元素就會自動置中:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>純CSS3實現同心圓 - 何問起</title>
 <meta charset="utf-8" />
<style>
.framehovertree {
position: relative;
margin: 100px auto;
width: 300px;
height: 300px;
border-radius: 150px;
border: 1px solid green;
background-color:green;
}
.centerhovertree {
width: 150px;
height: 150px;
background-color:red;
position: absolute;
border-radius: 50%;
z-index: 999;
margin:auto;
left:0px ;right:0px;
top:0px;bottom:0px;
text-align:center;line-height:150px;
color:white;
}
</style>
</head>
<body>
<div class="framehovertree">
<div class="centerhovertree">何問起 同心圓</div>
</div>
</body>
</html>

line-height 等於圓的直徑,文字便自然垂直居中;加上 text-align:center 就完成水平居中。相較之下,純 CSS 版本沒有任何腳本依賴、效能更好,是靜態版面首選;jQuery 版本則在需要依資料決定尺寸時更靈活。

實際渲染結果:何問起 同心圓

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved