最终效果是:当单击“放大”“缩小”按钮时可以逐次增加段落文字的大小。
1.获取当前段落文字的字号大小
var thisEle = $("#para").css("font-size");
2.把获取的字号大小分解成“数字”和“单位”两部分
var textFontSize = parseFloat(thisEle,10);
var unit = thisEle.slice(-2);
3.给"放大"“缩小”按钮添加事件
$("span").click(function(){
var cName = ($(this).attr("class"))
if(cName == "bigger"){
textFontSize+=2;
}else if(cName == "smaller"){
textFontSize-=2;
}
$("#para").css("font-size",textFontSize+unit)
})
完整代码:
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>网页字体大小</title>
<script type="text/javascript" src="jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function(){
var thisEle = $("#para").css("font-size"); //获取当前段落的字号大小
var textFontSize = parseFloat(thisEle,10); //获取字号大小中的数字部分
var unit = thisEle.slice(-2);//获取字号大小中的单位部分
$("span").click(function(){
var cName = ($(this).attr("class"))
if(cName == "bigger"){
textFontSize+=2;
}else if(cName == "smaller"){
textFontSize-=2;
}
$("#para").css("font-size",textFontSize+unit)
})
})
</script>
<style type="text/css">
* { 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>
</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. This is some text. This is some text. This
is some text. This is some text. This is some text. This is some text. This is some
text. This is some text. This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text. This is some text. This
is some text. This is some text.
</p>
</div>
</div>
</body>
</html>
注释:
1.parseFloat() 函数可解析一个字符串,并返回一个浮点数。http://www.w3school.com.cn/js/jsref_parseFloat.asp
2.slice() 方法可提取字符串的某个部分,并以新的字符串返回被提取的部分。http://www.w3school.com.cn/js/jsref_slice_string.asp