1. 程式人生 > >jQuery控制網頁字型大小

jQuery控制網頁字型大小

<div class="msg">
    <div class="msg_caption">
        <button type="button" class="bigger">放大</button>
        <button type="button" class="smaller">縮小</button>
    </div>
    <div>
        <p class="para" >
            “On an evening in the latter part of May a middle-aged man 
            was walking homeward from Shaston to the village of Marlott, 
            in the adjoining Vale of Blakemore, or Blackmoor. 
            The pair of legs that carried him were rickety, 
            and there was a bias in his gait which inclined him 
            somewhat to the left of a straight line. 
            He occasionally gave a smart nod, 
            as if in confirmation of some opinion, 
            though he was not thinking of anything in particular. 
            An empty egg-basket was slung upon his arm, 
            the nap of his hat was ruffled, 
            a patch being quite worn away at its brim 
            where his thumb came in taking it off. 
            Presently he was met by an elderly parson astride on a gray mare, 
            who, as he rode, hummed a wandering tune.”
        </p>
    </div>
</div>
<script>
    $(function(){
        $("button").click(function(){
            var fontSize = $(".para").css("font-size");  //獲取字型大小
            var textFontSize = parseInt(fontSize);  //去掉單位
            var unit = fontSize.slice(-2);  //獲取單位
            var btn = $(this).attr("class"); //獲取button的屬性值
            if(btn == "bigger"){
                if(textFontSize <= 30){  //判斷最大字型
                    textFontSize += 2;
                }
            } else if(btn == "smaller"){
                if(textFontSize >= 14){  //判斷最小字型
                    textFontSize -= 2;
                }
            }
            $(".para").css("font-size",textFontSize + unit);
        });
    })
</script>