简体   繁体   中英

Select external CSS using tag Option with OnChange function

My goal is to change the site to different external css using a dropdown list and then save it as a cookie, this is how far I've come. I need help to solve it with onchange in an external js file. I must use javascript for this. Thank you very much in advance!

(sorry for the bad coding)

HTML:

<head>

<link rel="stylesheet" type="text/css" href="style1.css" title="stil1" >
<link rel="stylesheet" type="text/css" href="style2.css" title="stil2" >
<link rel="stylesheet" type="text/css" href="style3.css" title="stil3" >
<link rel="stylesheet" type="text/css" href="style4.css" title="stil4" >

<pre>
<script type="text/javascript" src="test.js">

</script>

</pre>
</head>

<body>

    <select id="dropdown">
        <option value="1" >Utseende 1</option>
        <option value="2" >Utseende 2</option>
        <option value="3" >Utseende 3</option>
        <option value="4" >Utseende 4</option>
    </select>

</body>

External JS:

function createCookie(name,value,days){

   if (days){
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
   }
   else expires = "";
   document.cookie = name+"="+value+expires+"; path=/";
   }


function readCookie(name){

    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
    }


function changeStyle(style){

    createCookie("style", style, 30);

    var links = document.getElementsByTagName("link");

    for(var i=0; i<4; i++){
    if(i == style){
    links[i].disabled = false;
    }
    else{
    links[i].disabled = true;
    }
    }
    }


var drop = document.getElementById("dropdown").getElementsByTagName("option");

    for(var i = 1; i < drop.length; i++){

    drop[i].onchange = function(){

    changeStyle(i-1);

    }

    }


function init(){

    var style = readCookie("style");

    if (style == null){
    style = 0;
    }
    changeStyle(style);
    }

You can do this as following:

$("#dropdown").change(function() {
    $("link").attr("href", "style"+$(this).val()+".css");                      
});

DEMO HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM