【问题标题】:Add a css file with JS [duplicate]用JS添加一个css文件[重复]
【发布时间】:2014-10-29 06:08:00
【问题描述】:

我在这里找到了一些关于我的问题的问题,但我无法使用它。 我将通过 JS、JQuery 在单击它们时更改 css 属性

 <!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <script src="../scripts/jquery-1.11.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="../css/styles.css">
    <script src="../scripts/javascript.js"></script>
</head>
<body>
<div class="osn">
<span>Green</span>
</div>
<div class="osb">
    <span>Red</span>
</div>
</body>
</html>
<script>
/*$( document ).ready(function () { 
    $(".osn").mouseover(function() { 
        uploadcss()
        });
});*/
$( document ).ready(function () { 
    $(".osn").click(function addcss (csslink){});
});
</script>

还有我的 javascript.js

function uploadcss() {$(".osb").css("border","15px solid blue")};
function downloadcss() {$(".osb").css("border","5px solid red")};

function addcss (csslink) {
    var csslink = document.cretaeElement ("link");
    csslink.rel = "stylesheet";
    csslink.type = "text/css";
    csslink.href="../css/test.css";
}

它不起作用:(为什么?

【问题讨论】:

  • cretaeElement ?而你只是创建一个元素,你不添加它?
  • @ChrisHawkes 投票关闭并将其标记为重复
  • 在控制台出现任何错误。

标签: javascript jquery html css


【解决方案1】:
  <script>
   function addcss () {
    var csslink = document.createElement("link");
    csslink.rel = "stylesheet";
    csslink.type = "text/css";
    csslink.href="../css/test.css";
    document.getElementsByTagName("head")[0].appendChild(csslink); 
    return false;
   }  

   window.onload = function() {
     document.getElementById("mylink").onclick = addcss(); 
   }; 
  </script>

 <a href="#" id="mylink">mylink</a> 

您需要将其附加到头部。

【讨论】:

  • 嗨,我如何通过点击 div 正确运行这个 JS
  • 在页面加载时将该函数添加为事件处理程序。将脚本放入页面中。
  • marko 一切正常。 THX!!!!!!!!!!!!!!!
  • 我的 JS 有错误。我有 cretaeElement,我需要 createElement
【解决方案2】:

尝试类似:

$(function(){

  $(".my-btn").on('click', function(){
     loadCSS("path/to/style.css");
  });

  function loadCSS(href) {
     var cssLink = $("<link rel='stylesheet' type='text/css' href='"+href+"'>");
     $("head").append(cssLink); 
 };
})

【讨论】:

    【解决方案3】:

    试试这个

    $(document).ready(function () {
       $(".osn").click(function(){
           $('head').append('<link href="cssFolder/sheet2.css" rel="stylesheet" id="stylenew" />');
    });
    

    【讨论】:

      猜你喜欢
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 2020-12-17
      • 2020-04-08
      相关资源
      最近更新 更多