>  기사  >  웹 프론트엔드  >  jQuery를 사용하여 CSS 파일을 동적으로 로드하는 단계에 대한 자세한 설명

jQuery를 사용하여 CSS 파일을 동적으로 로드하는 단계에 대한 자세한 설명

php中世界最好的语言
php中世界最好的语言원래의
2018-04-23 15:54:552181검색

이번에는 jQuery를 사용하여 CSS 파일을 동적으로 로드하는 단계에 대해 자세히 설명하겠습니다. jQuery에서 CSS 파일을 동적으로 로드할 때의 주의 사항은 무엇입니까?

때때로 페이지 레이아웃을 전환할 때와 같이 외부 CSS 파일을 로드하기 위해 jQuery를 사용해야 할 수도 있습니다. 아이디어는 링크 요소를 생성하고 이를 태그에 추가하는 것입니다. 먼저 jQuery를 사용하여 이를 구현하는 방법을 살펴보겠습니다.

다음은 제가 가장 좋아하는 글쓰기 방식입니다:

$("<link>")
.attr({ rel: "stylesheet",
type: "text/css",
href: "site.css"
})
.appendTo("head");

어떤 친구들은 아래 글쓰기 방식을 사용할 수도 있지만 형식은 약간 다르지만(appendTo 추가) 원칙은 여전히 ​​동일합니다.

$("head").append("<link>");
css = $("head").children(":last");
css.attr({
rel: "stylesheet",
type: "text/css",
href: "/Content/Site.css"
});

마지막으로 일부 친구는 javascript에서 직접 사용하고 싶을 수도 있습니다. 방법은 다음과 같습니다.

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);
}

웹 상호 작용 중이라면 위의 방법을 사용하여 jQuery 또는 javascript를 통해 CSS 파일을 도입할 수 있습니다. 원래 방법을 사용하는 것이 좋습니다.

이제 js와 css를 로드할 수 있는 예제도 소개합니다

코드는 다음과 같습니다

$.extend({
includePath: '',
include: function(file) {
var files = typeof file == "string" ? [file]:file;
for (var i = 0; i < files.length; i++) {
var name = files[i].replace(/^s|s$/g, "");
var att = name.split(&#39;.&#39;);
var ext = att[att.length - 1].toLowerCase();
var isCSS = ext == "css";
var tag = isCSS ? "link" : "script";
var attr = isCSS ? " type=&#39;text/css&#39; rel=&#39;stylesheet&#39; " : " language=&#39;javascript&#39; type=&#39;text/javascript&#39; ";
var link = (isCSS ? "href" : "src") + "=&#39;" + $.includePath + name + "&#39;";
if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">");
}
}
});
//使用方法
$.includePath = 'http://hi.xxx/javascript/'; 
$.include(['json2.js', 'jquery.tree.js', 'jquery.tree.css']);

완전한 예제

index.html

<!-- Created by Barrett at RRPowered.com -->
<!-- File name index.html -->
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax
/libs/jquery/1.4.4/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="default.css">
<title>A simple jQuery image slide</title>
<script type="text/javascript">
$(function(){
$(".theme").click(function(){
var theme=$(this).attr("rel");
$("link").attr("href",$(this).attr('rel'));
$("head").append("<link>");
});
});
</script>
</head>
<body>
<p class="theme" rel="blue.css">Blue</p>
<p class="theme" rel="orange.css">Orange</p>
<p class="theme" rel="yellow.css">Yellow</p>
<p class="theme" rel="default.css">Default</p>
<p class="container">
<p class="menu">Tab1 Tab2 Tab3 Tab4 Tab5</p>
<p class="inner">
Lorem ipsum dolor sit amet
</p>
<p class="footer">copyright yoursite 2011</p>
</p>
</body>
</html>
default.css
body{
background-color:#ffffff;
font-family:"arial";
}
.theme{
margin:10px;
width:70px;
padding:5px;
text-align:center;
background-color:#BEF781;
border:solid #333333 1px;
color:#444444;
font-weight:bold;
cursor:pointer;
}
.container{
margin-left:auto;
margin-right:auto;
width:700px;
}
.inner{
padding:20px;
border:solid #333333 1px;
}
.menu{
background-color:#f2f2f2;
padding:10px;
font-weight:bold;
}
.footer{
background-color:#f9f9f9;
padding:5px;
}
blue.css
body{
background-color:#2E9AFE;
font-family:"arial";
}
.theme{
margin:10px;
width:70px;
padding:5px;
text-align:center;
background-color:#BEF781;
border:solid #333333 1px;
color:#444444;
font-weight:bold;
cursor:pointer;
}
.container{
margin-left:auto;
margin-right:auto;
width:700px;
}
.inner{
padding:20px;
border:solid #333333 1px;
background-color:#58ACFA;
color:#ffffff;
}
.menu{
background-color:#f2f2f2;
padding:10px;
font-weight:bold;
}
.footer{
background-color:#f9f9f9;
padding:5px;
}
yellow.css
body{
background-color:#F7FE2E;
font-family:"arial";
}
.theme{
margin:10px;
width:70px;
padding:5px;
text-align:center;
background-color:#BEF781;
border:solid #333333 1px;
color:#444444;
font-weight:bold;
cursor:pointer;
}
.container{
margin-left:auto;
margin-right:auto;
width:700px;
}
.inner{
padding:20px;
border:solid #333333 1px;
background-color:#f6f6f6;
}
.menu{
background-color:#F2F5A9;
padding:10px;
font-weight:bold;
}
.footer{
background-color:#F2F5A9;
padding:5px;
}
orange.css
body{
background-color:#FE9A2E;
font-family:"arial";
}
.theme{
margin:10px;
width:70px;
padding:5px;
text-align:center;
background-color:#BEF781;
border:solid #333333 1px;
color:#444444;
font-weight:bold;
cursor:pointer;
}
.container{
margin-left:auto;
margin-right:auto;
width:700px;
}
.inner{
padding:20px;
background-color:#F7BE81;
color:#404040;
}
.menu{
background-color:#ffffff;
padding:10px;
font-weight:bold;
color:#FFBF26;
}
.footer{
background-color:#ffffff;
padding:5px;
color:#FFBF26;
}

여기서 사례를 읽으신 후 방법을 마스터하셨으리라 믿습니다. 기사, 더 흥미로운 정보를 보려면 오세요. PHP 중국어 웹사이트에서 다른 관련 기사도 주목하세요!

추천 도서:

jquery의 시간 획득 방법 요약

jQuery 버전 업그레이드 시 주의사항은 무엇인가요

위 내용은 jQuery를 사용하여 CSS 파일을 동적으로 로드하는 단계에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.