JavaScript实现样式表的简单切换

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style type="text/css">
        #ulList
        {
             height:18px;
             width:120px;
             padding-left:380px;
             padding-top:66px;
        }
        #ulList li
        {
            list-style-type:none;
            display:inline-block;
            height:18px;
            width:30px;
            text-align:center;
        }
        #div1
        {
            width:500px;
            height:100px;
            border:1px solid #000000;
            margin:0 auto;
        }
    </style>
    <link href="#" rel="stylesheet" id="csslink" />
    <script type="text/javascript">
        var data = [
            { cid: "1", color: "blue", cssPath: "css\blue.css" },
            { cid: "2", color: "red", cssPath: "css\red.css" },
            { cid: "3", color: "yellow", cssPath: "css\yellow.css" },
            { cid: "4", color: "green", cssPath: "css\green.css" }];

        var ulList;

        window.onload=function()
        {
            ulList = document.getElementById("ulList");

            for(var i=0;i<ulList.children.length;i++)
            {
                //给li设置属性cid
                ulList.children[i].setAttribute("cid", data[i].cid);
                //通过cid设置li的背景色
                ulList.children[i].style.backgroundColor = setColor(ulList.children[i].getAttribute("cid"));
                //通过cid获取cssPath
                ulList.children[i].onclick =function()
                {
                    var csslink = document.getElementById("csslink");
                    csslink.href = liClick(this.getAttribute("cid"));
                   // csslink.href = "css/" + this.style.backgroundColor + ".css";
                }
            }
        }

        //通过cid获取颜色
        function setColor(cid)
        {
            for(var j=0;j<data.length;j++)
            {
                if(data[j].cid==cid)
                {
                    return data[j].color;
                }
            }
        }

        //点击li更换div背景色
        function liClick(cid)
        {
            for (var j = 0; j < data.length; j++)
            {
                if (data[j].cid == cid)
                {
                    return data[j].cssPath;
                }
            }
        }
    </script>
</head>
<body>
    <div id="div1">
        <ul id="ulList">
            <li>1</li><li>2</li><li>3</li><li>4</li>
        </ul>
    </div>
</body>
</html>

效果图如下:点击其中任意颜色,div的背景色也随着改变,JS基础~~~权当练练手~~~

  

原文地址:https://www.cnblogs.com/miaoying/p/5272589.html