【问题标题】:Switch CSS file on button click在按钮单击时切换 CSS 文件
【发布时间】:2012-03-07 20:05:58
【问题描述】:

我想通过单击 asp.net 中的按钮来切换页面的 CSS,但不知何故不能这样做。我的代码如下:

HTML:

<div>
    <h1>My Website</h1>
    <br/>
    <button>Night Mode</button>
    <button>Day Mode</button>
    </div>

脚本:

<script>
        $(function () {
            $('button').click(function () {

               $('link').attr('href', 'Styles/night.css');
            });

        });
    </script>

标题:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

 <link  href="Styles/day.css" rel="stylesheet" type="text/css" />

我在 Styles 文件夹中有 2 个 css 文件,分别是 day.css 和 night.css。该页面正在使用 day.css,点击任何按钮时应切换到 night.css。

如果我将 .html 文件和两个 .css 文件放在一个文件夹中,它实际上可以工作。但是在 Visual Studio(即 aspx 页面)中,它没有发生。我尝试了其他 jQuery 代码,例如 alert,它工作正常。 之后我可以通过使用切换等来改进我的代码。

【问题讨论】:

    标签: jquery asp.net css webforms


    【解决方案1】:

    从戴夫·沃德那里得到了答案。 我所要做的就是包含 preventDefault() 方法。覆盖表单的默认行为。

    【讨论】:

      【解决方案2】:

      根据您的要求,此 sn-p 将为您提供帮助。

      按照以下步骤操作:

      您必须在同一位置创建两个 css 文件。

      1:Day.css

      2:Night.css

      之后使用此代码切换 css 文件。

      <html>
      <head>
      <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
         <link href="Day.css" id="styles" rel="stylesheet" type="text/css" />
      
      </head>
      <script>
      $(document).ready(function(){
      $('#mode').click(function(){
      if($('link#styles').attr('href')=="Day.css"){
      $('#mode').attr('value','Switch To Day Mode')
      $('link#styles').attr('href','Night.css')
      }
      else
      {
      $('#mode').attr('value','Switch To Night Mode')
      $('link#styles').attr('href','Day.css')
      }
      })
      
      });
      </script>
      <div class="table-responsive container">
      <input type=button id="mode" text="Switch Mode" class="btn btn-primary" value="Switch To Night Mode" >  </div>
        </html>
      

      【讨论】:

        【解决方案3】:

        为链接添加一个 id attr 并尝试删除链接,然后将新链接附加到该链接

        var newstyle = $("#style").clone().attr("link","newstyle.css");
        $("#style").remove().after(newstyle);
        

        【讨论】:

        • 我添加了一个id作为'style'链接并修改代码如下: var newstyle = $("#style").clone().attr("link", "Styles/night. css"); $("#style").remove().after(newstyle);先生仍然没有工作。
        猜你喜欢
        • 1970-01-01
        • 2015-04-14
        • 2012-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-10
        • 1970-01-01
        相关资源
        最近更新 更多