如何使用JavaScript加载外部Css文件



我试图通过JavaScript调用css外部文件,但它不工作,请帮助我。如何通过JavaScript调用外部css页面。当我运行上面的代码css不反映在浏览器上。

<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<!--<link rel="stylesheet" type="text/css" href="C:UsersNaniDesktopworkNew folderlayout.css"> -->
</head>
<body>

<div class="header">
<h1>My Website</h1>
<p>A <b>responsive</b> website created by me.</p>
</div>

<div class="navbar">
<a href="#" class="active">Home</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#" class="right">Link</a>
</div>

<div class="row">
<div class="side">

<h2>About Me</h2>
<h5>Photo of me:</h5>
<div class="fakeimg" style="height:200px;">
Image</div>
<p>Some text about me in culpa qui officia deserunt mollit anim..</p>
<h3>More Text</h3>
<p>Lorem ipsum dolor sit ame.</p>
<div class="fakeimg" style="height:60px;">Image</div><br>
<div class="fakeimg" style="height:60px;">Image</div><br>
<div class="fakeimg" style="height:60px;">Image</div>
</div>
<div class="main">
<h2>TITLE HEADING</h2>
<h5>Title description, Dec 7, 2017</h5>
<div class="fakeimg" style="height:200px;">Image</div>
<p>Some text..</p>
<p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.</p>
<br>
<h2>TITLE HEADING</h2>
<h5>Title description, Sep 2, 2017</h5>
<div class="fakeimg" style="height:200px;">Image</div>
<p>Some text..</p>
<p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.</p>
</div>
</div>

<div class="footer">
<h2>Footer</h2>
</div>
<noscript>

</noscript>
<script>
(function() {
var cssMain = document.createElement('link');
cssMain.href = 'C:UsersNaniDesktopworkNew folderlayout.css';
cssMain.rel = 'stylesheet';
cssMain.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(cssMain);
})();


</script>
</body>
</html>

将css文件添加到项目中,并使用相对路径而不是指定的完整路径。例如:

<link rel="stylesheet" type="text/css" href="./css/layout.css">
</head>

如果你想通过javascript加载它,你可以使用insertAdjacentHTML,它可以完成这一行。

document.getElementsByTagName("head")[0].insertAdjacentHTML(
"beforeend",
"<link rel="stylesheet" href="path/to/style.css" />");

insertAdjacentHTML - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

相关内容

  • 没有找到相关文章

最新更新