1. 程式人生 > >jQuery控制網頁字體大小和膚色

jQuery控制網頁字體大小和膚色

新網 其中 utf jquery siblings substring fin -c ssi

在一些網站上經常看到有控制網頁膚色和字體大小的功能,接下來,我們將用兩個例子來實現這兩個功能。

網頁字體大小

首先我們在網頁中添加一些被控制大小的文字和字體控制的按鈕。

<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
 <script src="../scripts/jquery-1.3.1.js" type="text/javascript"></
script> </head> <body> <div class="msg"> <div class="msg_caption"> <span class="bigger" >放大</span> <span class="smaller" >縮小</span> <span >20</span> <span >18</span> <span >16</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>

技術分享圖片

有兩種控制字體大小的方式:在當前字體大小的基礎上放大或縮小,直接選擇字號進行控制。

首先是第一種,需要獲取當前文字的字體大小,獲取的值是帶單位的數值,我們在進行放大縮小操作時,需要進行加減運算,所以需要用parseInt()方法去掉單位再進行運算,運算後的值需要加上單位後再賦值給需要控制的文字,但是需要註意的是,無限放大和縮小並不合適,所以在操作時,需要給一個最大和最小字體。

第二種方式就比較簡單了,直接通過點擊獲取字體大小的數值,然後加上單位就可以進行賦值添加樣式了。

<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;
                    }
            }else{
                textFontSize = $(this).text();
            }
            $("#para").css("font-size",  textFontSize + unit);
        });
    });
  </script>

2,網頁換膚

網頁換膚的原理是通過調用不同的樣式表文件來實現不同皮膚的切換,並且需要將換好的皮膚記入Cookie中,這樣用戶下次訪問時,就可以顯示用戶自定義的皮膚了。

首先設置HTML結構:

<!DOCTYPE>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="css/default.css" rel="stylesheet" type="text/css" />
    <script src="../scripts/jquery-1.3.1.js" type="text/javascript"></script>
</head>
<body>
    <ul id="skin">
        <li id="skin_0" title="灰色" class="selected">灰色</li>
        <li id="skin_1" title="紫色">紫色</li>
        <li id="skin_2" title="紅色">紅色</li>
        <li id="skin_3" title="天藍色">天藍色</li>
        <li id="skin_4" title="橙色">橙色</li>
        <li id="skin_5" title="淡綠色">淡綠色</li>
    </ul>

    <div id="div_side_0">
        <div id="news">
            <h1 class="title">時事新聞</h1>
        </div>
    </div>

    <div id="div_side_1">
        <div id="game">
            <h1 class="title">娛樂新聞</h1>
        </div>
    </div>
</body>
</html>

其中基礎樣式為:

*{
    margin:0px;
    padding:0px;
}
body {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 12px;
}
#div_side_0,#div_side_1
{
    float:left;
    width:120px;
    height:450px;
    }
#skin
{
    margin:10px;
    padding:5px;
    width:210px;
    padding-right:0px;
    list-style:none;
    border: 1px solid #CCCCCC;
    overflow:hidden;
    }
#skin li{
    float:left;
    margin-right:5px;
    width:15px;
    height:15px;
    text-indent:-999px;
    overflow:hidden;
    display:block;
    cursor:pointer;
    background-image:url(theme.gif);
}
#skin_0{
    background-position:0px 0px;
}
#skin_1{
    background-position:15px 0px;
}
#skin_2{
    background-position:35px 0px;
}
#skin_3{
    background-position:55px 0px;
}
#skin_4{
    background-position:75px 0px;
}
#skin_5{
    background-position:95px 0px;
}
#skin_0.selected{
    background-position:0px 15px !important;
}
#skin_1.selected{
    background-position:15px 15px !important;
}
#skin_2.selected{
    background-position:35px 15px !important;
}
#skin_3.selected{
    background-position:55px 15px !important;
}
#skin_4.selected{
    background-position:75px 15px !important;
}
#skin_5.selected{
    background-position:95px 15px !important;
}
.title
{
    cursor:pointer;}
h1{
   margin:10px;
   padding:10px 20px;
   width:60px;
   color:#ffffff;
   font-size:14px;
}
a:link {
    text-decoration: none;
    color: #333333;
}
a:visited {
    color: #333333;
    text-decoration: none;
}
a:hover {
    color: #000000;
    text-decoration: underline;
}

然後根據HTML代碼預定義幾套換膚用的樣式,分別有灰色、紫色、紅色等,在本次的實例中為了簡化,只是進行簡單的背景替換,所以在這些樣式文件中只有對於的背景顏色:

/*skin_0.css*/ h1{   background:#999999; }

在初始化的時候,默認選擇灰色,後期將通過更改樣式表鏈接來更換顏色,所以,我們需要為添加背景色的樣式表鏈接添加一個id,方便後期修改。

 <link href="css/skin_0.css" rel="stylesheet" type="text/css" id="cssfile" />

網頁的初始化效果如下:
技術分享圖片

接下來,將通過點擊皮膚選擇按鈕來實現換膚。

首先,選中顏色後,為當前點擊的元素添加選中樣式。

var $li =$("#skin li");
$li.click(function(){
      $("#"+this.id).addClass("selected")             
              .siblings().removeClass("selected");  
})

其次,設置網頁的皮膚顏色。

$(function(){
    var $li =$("#skin li");
    $li.click(function(){
          $("#"+this.id).addClass("selected")                
                 .siblings().removeClass("selected"); 
          $("#cssfile").attr("href","css/"+this.id+".css"); 
    })
})

此時,簡易版的換膚就實現了,但是,當用戶刷新網頁或者關閉瀏覽器後,皮膚又會被初始化,因此,我們需要將當前選擇的皮膚進行保存。

這裏,我們需要進入jQuery的cookie插件

jQuery.cookie = function(name, value, options) {
    if (typeof value != ‘undefined‘) { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = ‘‘;
            options.expires = -1;
        }
        var expires = ‘‘;
        if (options.expires && (typeof options.expires == ‘number‘ || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == ‘number‘) {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = ‘; expires=‘ + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? ‘; path=‘ + (options.path) : ‘‘;
        var domain = options.domain ? ‘; domain=‘ + (options.domain) : ‘‘;
        var secure = options.secure ? ‘; secure‘ : ‘‘;
        document.cookie = [name, ‘=‘, encodeURIComponent(value), expires, path, domain, secure].join(‘‘);
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != ‘‘) {
            var cookies = document.cookie.split(‘;‘);
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + ‘=‘)) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

然後將當前的皮膚保存進cookie,保存後,就可以通過cookie來獲取當前的皮膚了,如果cookie存在,則將當前皮膚設置為cookie記錄的值,這樣,當用戶刷新網頁後,仍然是當前選擇的皮膚。

完整代碼如下:

<!DOCTYPE>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="css/default.css" rel="stylesheet" type="text/css" />
    <link href="css/skin_0.css" rel="stylesheet" type="text/css" id="cssfile" />
    <script src="../scripts/jquery-1.3.1.js" type="text/javascript"></script>
    <script src="js/jquery.cookie.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function(){
            var $li =$("#skin li");
            $li.click(function(){
                $("#"+this.id).addClass("selected")               
                            .siblings().removeClass("selected");  
                $("#cssfile").attr("href","css/"+ (this.id) +".css"); //設置不同膚色
                $.cookie( "MyCssSkin" ,  this.id , { path: /, expires: 10 });//存入cookie
            });
            var cookie_skin = $.cookie( "MyCssSkin");  //獲取cookie
            if (cookie_skin) {  
                //如果存在cookie
                    $("#"+cookie_skin).addClass("selected")               
                                      .siblings().removeClass("selected");  
                    $("#cssfile").attr("href","css/"+ cookie_skin +".css");
                    $.cookie( "MyCssSkin" ,  cookie_skin  , { path: /, expires: 10 });
            }
        })
    </script>
</head>
<body>
    <ul id="skin">
        <li id="skin_0" title="灰色" class="selected">灰色</li>
        <li id="skin_1" title="紫色">紫色</li>
        <li id="skin_2" title="紅色">紅色</li>
        <li id="skin_3" title="天藍色">天藍色</li>
        <li id="skin_4" title="橙色">橙色</li>
        <li id="skin_5" title="淡綠色">淡綠色</li>
    </ul>

    <div id="div_side_0">
        <div id="news">
            <h1 class="title">時事新聞</h1>
        </div>
    </div>

    <div id="div_side_1">
        <div id="game">
            <h1 class="title">娛樂新聞</h1>
        </div>
    </div>
    
</body>
</html>

jQuery控制網頁字體大小和膚色