jQuery - css - dynamic change style

最近工作上所開發的網頁系統,打算把切換介面風格的功能做上去,於是研究了一下如何動態改變CSS並且套用,發現還挺簡單的~ 只需要置換網頁所Link的CSS file即可,以下弄個實際範例,透過jQuery來操作:

首先我們建立一個簡單的網頁
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" type="text/css" href="style_1.css" class="pagestyle" id="style_1" />
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div class="outborder" id="div_1">
<div class="inline">Sample text</div>
</div>
</body>
</html>


這個網頁所使用的CSS file為style_1.css,其內容如下:

/*
 *  Style 1
 */
body { text-align:center; }
.outborder { padding:5px; background:red; }
.inline { padding:5px; color:black; font-size:40px; font-weight:bold; background:yellow; }

接下來我們建立第二種風格,檔案為style_2.css

/*
 *  Style 2
 */
body { text-align:center; }
.outborder { padding:5px; background:blue; }
.inline { padding:5px; color:black; font-size:40px; font-weight:bold; background:lightblue; }

然後為了簡便操作,我們透過click畫面上的文字框來做切換,jQuery如下:

$(document).ready(function()
{
$('#div_1').click(changeCssFile);
});

function changeCssFile()
{
var $oldCss = $('head link.pagestyle');
if ($oldCss.attr('id') == 'style_1')
{
var $newCss = $('<link />')
.attr('rel', 'stylesheet')
.attr('type', 'text/css')
.attr('href', 'style_2.css')
.attr('class','pagestyle')
.attr('id','style_2');
$oldCss.replaceWith($newCss);
}
else
{
var $newCss = $('<link />')
.attr('rel', 'stylesheet')
.attr('type', 'text/css')
.attr('href', 'style_1.css')
.attr('class','pagestyle')
.attr('id','style_1');
$oldCss.replaceWith($newCss);
}
}

最後測試!










留言

這個網誌中的熱門文章

HTML - CSS - footer floating toolbar bottom 瓢浮置底的工具列

jQuery - header & floating menu - dynamic detect & adjust

自己設計讓網頁支援多國語系的架構