2014-09-04 99 views
-3

我在這裏發現了一些關於我的問題的問題,但我無法使用它。 通過JS點擊它們時我會改變的CSS屬性,JQuery的用JS添加一個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"; 
} 

而且它不工作:(爲什麼?

+1

'cretaeElement'?你只是創建一個元素,你不添加它? – 2014-09-04 13:09:31

+0

錯誤是什麼? – steo 2014-09-04 13:10:12

+0

dup question - > http://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript – 2014-09-04 13:10:38

回答

0
<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> 

您需要將它追加到頭部。

+0

嗨,以及如何通過點擊div – AndreyPr 2014-09-04 13:31:21

+0

正確運行此JS添加該函數作爲頁面加載時的事件處理程序。將腳本放在頁面中。 – marko 2014-09-04 13:50:55

+1

marko一切正常。謝謝!!!!!!!!!!!!!!! – AndreyPr 2014-09-04 14:01:52

0

嘗試喜歡的東西:

$(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); 
}; 
}) 
0

試試這個

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