使用JS实现网页动态换肤

现在很多网站都有换肤功能,通过切换风格可以让同一个网站带给用户不一样的体验,那么如何动态切换风格呢?
我们现在的网站都是结构,表现,行为分离,所以我们可以通过切换CSS样式来更改页面风格。
如果你的网站使用了jQuery,那么我们可以定义一个jQuery扩展方法,用来动态切换CSS样式
代码如下:

jQuery.extend({
    //根据ID查找样式,如果存在则删除这个样式
    removeStyleSheet: function(id) {
        var existing = document.getElementById(id);
        if (existing) {
            existing.parentNode.removeChild(existing);
        }
    }, 
    //风格切换  id:样式标识ID   url:样式路径
    swapStyleSheet: function(id, url) {
        var doc = document;
        this.removeStyleSheet(id);
        var ss = doc.createElement("link");
        ss.setAttribute("rel", "stylesheet");
        ss.setAttribute("type", "text/css");
        ss.setAttribute("id", id);
        ss.setAttribute("href", url);
        doc.getElementsByTagName("head")[0].appendChild(ss);
    }
});

然后我们就可以在调用这个方法来实现换肤功能:

$.swapStyleSheet("DefaultStyle", "Styles/DefaultStyle.css");

如果你的网站样式比较固定 那么可以使用以下的JS方法:

function C(id) {
    return !id ? null : document.getElementById(id);
}
// 风格切换  cssname css文件名
function themestyle(cssname) {
    if (!C('themestyle')) {
        css = document.createElement('link');
        css.id = 'themestyle',
        css.type = 'text/css';
        css.rel = 'stylesheet';
        var headNode = document.getElementsByTagName("head")[0];
        headNode.appendChild(css);
    }
    // 引用的CSS文件的地址
    C('themestyle').href = 'Styles/' + cssname + '.css';
}

然后调用以上方法即可:themestyle("DefaultStyle");

posted @ 2011-07-19 13:38  Crazy Ma  阅读(3660)  评论(6编辑  收藏  举报