【问题标题】:How to change src attribute of a stylesheet如何更改样式表的 src 属性
【发布时间】:2016-12-23 22:47:11
【问题描述】:

我正在尝试通过单击一个按钮来更改 CSS 样式表。

<head>    
<link id='link01' rel="stylesheet" href="blue.css">  
</head>

JS

$('.pointcolors').click(function(){
    var theme = $(this).attr('data-theme') + '.css';
    console.log(theme); // green.css - it's ok
    $('#link01').attr('src', theme);
});

但是没有样式变化。什么都没有发生。
有什么帮助吗?

【问题讨论】:

标签: jquery css


【解决方案1】:

我认为:

$('#link01').attr('src', theme);

应该是:

$('#link01').attr('href', theme);

How to change the href for a hyperlink using jQuery

【讨论】:

    【解决方案2】:

    改变

     $('#link01').attr('src', theme);
    

    收件人:

     $('#link01').attr('href', theme);
    

    如果您查看链接标签,包含文件名的属性是“href”,而不是“src”。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      使用jQuery的.attr()来改变link标签的href属性。

      $(function() {
      	$("#block a").on('click', function() {
              theme = $(this).data('theme');
      		$("#link01").attr("href", theme + '.css');
              console.log("Stylesheet changed to: " + $("#link01").attr("href"));
      		return false;
      	});
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <link id='link01' rel="stylesheet" href="blue.css">  
      <div id="block">
        <a href="#" data-theme="green">Change Stylesheet Link</a>
      </div>

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        src 更改为href 应该可以工作。

        $('#link01').attr('href', theme);
        

        【讨论】:

          猜你喜欢
          • 2019-03-08
          • 2012-10-09
          • 2021-02-09
          • 1970-01-01
          • 1970-01-01
          • 2012-04-25
          • 2023-03-12
          • 2012-02-06
          • 1970-01-01
          相关资源
          最近更新 更多