使用 jQuery 加载 css 文件 http://www.jquery001.com/jquery-load-a-css-file.html
自己整合后代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
;(function ($) { $.H5G = { loadCss: function (cssPath, callback, target) { var css = $("<link>") .attr({ rel: "stylesheet", type: "text/css", href: cssPath }) .appendTo("head"); css.on("load", function () { if ($.isFunction(callback)) { callback(); } }); } , loadJs: function (jsPath, callback, target) { var script = $("<script>") .attr({ type: "text/javascript", src: jsPath }) .appendTo("head"); script.on("load", function () { if ($.isFunction(callback)) { callback(); } }); } } })(jQuery); |
下边是我喜欢的写法:
1 2 3 4 5 6 |
$("<link>") .attr({ rel: "stylesheet", type: "text/css", href: "site.css" }) .appendTo("head"); |
有些朋友可能会使用下边的写法,只是形式有些小差异(append appendTo),原理还是一样的。
1 2 3 4 5 6 7 |
$("head").append("<link>"); css = $("head").children(":last"); css.attr({ rel: "stylesheet", type: "text/css", href: "/Content/Site.css" }); |
最后,有的朋友可能希望直接在 javascript 中使用,方法如下:
1 2 3 4 5 6 7 |
function addCSS() { var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = '/Content/Site.css'; document.getElementsByTagName("head")[0].appendChild(link); } |
如果是在 web 交互时,我们可以使用上述的方法通过 jQuery 或者 javascript 来引入一个 css 文件,否则还是建议使用原始的方法。