使用jQuery和下拉菜单的简单样式表切换器

时间:2012-04-05 09:15:42

标签: javascript jquery function stylesheet

目前我有一个样式表切换器,它使用javascript根据下拉菜单中的选择加载新的样式表。

我想重新编写代码以使用jQuery而不是javascript。谁能帮我?我已经浏览过jQuery解决方案,虽然有很多,但没有使用下拉菜单。这是我的代码:

<head>

<link href="colour/light.css" rel="stylesheet" type="text/css">

<script type="text/javascript">
function changeScheme()
{ var _head = document.getElementsByTagName('head')[0];
  var _link = document.createElement('link');
_link.type = 'text/css';
_link.href = colour.colour.options[colour.colour.selectedIndex].value;
_link.rel = 'stylesheet';
_head.appendChild(_link);
}
</script>

</head>
<body>

<form action="#" name="colour" id="colour" onsubmit="return false;">
              <select name="colour" onchange="changeScheme();">
                <option value="colour/light.css">Light scheme</option>
                <option value="colour/dark.css">Dark scheme</option>
              </select>
            </form>

</body>

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

<head>

<link href="colour/light.css" rel="stylesheet" type="text/css" id="stylelink">

<script type="text/javascript">
function changeScheme()
{ 
  $('#stylelink').attr('href',$('#colourselector').val());
}
</script>

</head>
<body>

    <form action="#" name="colour" id="colour" onsubmit="return false;">
          <select id="colourselector" name="colour" onchange="changeScheme();">
            <option value="colour/light.css">Light scheme</option>
            <option value="colour/dark.css">Dark scheme</option>
          </select>
    </form>
</body>

答案 1 :(得分:0)

使您的解决方案100%jQuery(如建议的Stefan)

<head>
<link href="colour/light.css" rel="stylesheet" type="text/css" id="stylelink">

<script type="text/javascript">
$('#colourselector').change(function(){ 
  $('#stylelink').attr('href',$(this).val());
});
</script>

</head>
<body>
    <form action="#" name="colour" id="colour" onsubmit="return false;">
          <select id="colourselector" name="colour">
            <option value="colour/light.css">Light scheme</option>
            <option value="colour/dark.css">Dark scheme</option>
          </select>
    </form>
</body>