DIV CSS 佈局教程網

用 jQuery 實現網頁字體大小的即時調整
編輯:JQuery特效代碼     

無障礙設計中,讓使用者自行調整字體大小是很實用的功能。以下示範如何用 jQuery 實現字體的放大、縮小與恢復預設。

基本思路

在 HTML 標記下定義 font-size,透過三個 class(resetFont、increaseFont、decreaseFont)分別綁定點擊事件來實現相應操作:

/*
* 對頁面上的字體增大、縮小、恢復原始大小
* 需要在html頁面中定義三個元素
* 元素的class分別為 resetFont、increaseFont、decreaseFont
*/
$(function () {
//取得字體大小,在html標記下定義了font-size
var originalFontSize = $("html").css("font-size");
//恢復默認字體大小
$(".resetFont").click(function () {
$("html").css("font-size", originalFontSize);
return false;
});
//加大字體
$(".increaseFont").click(function () {
var currentFontSize = $("html").css("font-size");
var currentFontSizeNumber = parseFloat(currentFontSize);
var newFontSize = currentFontSizeNumber * 1.1;
$("html").css("font-size", newFontSize);
return false;
});
//減小字體
$(".decreaseFont").click(function () {
var currentFontSize = $("html").css("font-size");
var currentFontSizeNumber = parseFloat(currentFontSize);
var newFontSize = currentFontSizeNumber * 0.9;
$("html").css("font-size", newFontSize);
return false;
});
});

加上上下限的人性化版本

更進一步,可以為字體的放大與縮小加上限制,避免無意義的操作。當字體縮小到一定程度時,再點縮小就不會有任何作用,這樣的設計更為人性化:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>適時改變網頁字體大小,jQuery版</title>
<style>
* { margin:0; padding:0; }
.msg {width:300px; margin:100px; }
.msg_caption { width:100%; overflow:hidden; margin-bottom:1px;}
.msg_caption span { display:block; float:left; margin:0 2px; padding:4px 10px; background:#898989; cursor:pointer;font-size:12px;color:white; }
.msg textarea{ width:300px; height:80px;height:100px;border:1px solid #000;}
</style>
<!-- 引入jQuery -->
<script src="https://demo.poluoluo.com/jslib/jquery/jquery1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("span").click(function(){
var thisEle = $("#para").css("font-size");
var textFontSize = parseFloat(thisEle , 10);
var unit = thisEle.slice(-2); //獲取單位
var cName = $(this).attr("class");
if(cName == "bigger"){
if( textFontSize <= 22 ){
textFontSize += 2;
}
}else if(cName == "smaller"){
if( textFontSize >= 12 ){
textFontSize -= 2;
}
}
$("#para").css("font-size", textFontSize + unit);
});
});
</script>
</head>
<body>
<div class="msg">
<div class="msg_caption">
<span class="bigger" >放大</span>
<span class="smaller" >縮小</span>
</div>
<div>
<p id="para"> This is some text. This is some text.</p>
</div>
</div>
</body>
</html>

透過 parseFloat 去除單位並轉為數值,再配合上下限判斷,就能做出流暢又可控的字體縮放體驗。

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