【问题标题】:Simple Stylesheet switcher using jQuery and a dropdown menu使用 jQuery 和下拉菜单的简单样式表切换器
【发布时间】:2012-04-05 09:15:42
【问题描述】:

目前我有一个样式表切换器,它使用 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>

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery function stylesheet


    【解决方案1】:
    <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>
    

    【讨论】:

    • 谢谢,看起来应该可以了,但还是不行……我不知道为什么……
    • 您可以在 jQuery .change() 方法中定义处理程序,而不是使用 HTML onChange 属性调用函数:api.jquery.com/change/
    【解决方案2】:

    让您的解决方案 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2013-02-23
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多