简体   繁体   English

如何在纯JavaScript类中引用CSS文件

[英]How to reference CSS file in a javascript only class

I have a javascript file, and one of its functions is to create some HTML using javascript. 我有一个javascript文件,其功能之一是使用javascript创建一些HTML。

The HTML is created at runtime and creates the following element: HTML在运行时创建,并创建以下元素:

var oBox = document.createElement("notifiedusersbubble");
oBox.style.color="#808080";
oBox.style.display = "none";
oBox.style.position= "absolute";
oBox.style.width="200px";
oBox.style.border = '1px solid black';
oBox.style.background = "#DDEFF1";
oBox.style.fontFamily="arial,sans-serif";
oBox.style.padding="2px 2px 2px 4px";

Instead of leaving all the styling inside the javascript file, I want to put t in the CSS file and reference it from there. 而不是将所有样式保留在javascript文件中,我想将t放在CSS文件中并从那里引用它。

The problem is, I do not know how to do this using javascript. 问题是,我不知道如何使用javascript做到这一点。 I know that to do so using HTML I would write the following inside the <head> tag: 我知道要使用HTML这样做,我会在<head>标记内编写以下内容:

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

You can create a link element just like any other element: 您可以像创建其他任何元素一样创建一个link元素:

var link = document.createElement('link');
link.rel = "stylesheet";
link.type = "text/css";
link.href = "style.css";
document.querySelector("head").appendChild(link);

...but that said, I would normally expect you to leave that to the page author, just list it as a requirement of your script that the CSS must be put on the page — not least because it lets them combine that CSS with other CSS to avoid lots of HTTP requests, etc. That's what every major framework/library (jQuery UI, Bootstrap, etc.) does. ...但是那就是说,我通常希望您将其留给页面作者,只是将它作为脚本的要求列出,必须将CSS放在页面上-尤其是因为它使他们可以将CSS与其他CSS结合使用CSS避免了许多HTTP请求等。这就是每个主要框架/库(jQuery UI,Bootstrap等)所做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM