Javascript 为特定 DIV 加载外部 CSS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7379168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:02:42  来源:igfitidea点击:

Load an external CSS for a specific DIV

javascripthtmlcss

提问by Martin Marinov

So basically I have a page that has it's own CSS. On my server I have a folder of different CSS style files, so I want to have a "preview" window on my page for them. Can I somehow, maybe using javascript, apply an external CSS file only to a certain DIV, not to the entire page so I can get a "preview" of the custom CSS file? I'd rather not use iframes.

所以基本上我有一个页面,它有自己的 CSS。在我的服务器上,我有一个包含不同 CSS 样式文件的文件夹,所以我想在我的页面上为它们提供一个“预览”窗口。我能否以某种方式,也许使用 javascript,将外部 CSS 文件仅应用于某个 DIV,而不是整个页面,以便我可以获得自定义 CSS 文件的“预览”?我宁愿不使用 iframe。

采纳答案by Quentin

CSS applies to entire documents.

CSS 适用于整个文档。

If you want to limit the scope, then you need to make use of a descendent selector.

如果要限制范围,则需要使用后代选择器。

e.g. #id_of_div .the .rest .of .the .selector {}

例如 #id_of_div .the .rest .of .the .selector {}

You have to apply this to every selector, and take into account groups(so it isn't as simple as just prefixing the whole stylesheet and suffixing every })

您必须将其应用于每个选择器,并考虑(因此它并不像在整个样式表前加上后缀那么简单}

You would also find the stylesheet for the main document applying to your preview.

您还可以找到适用于您的预览的主文档的样式表。

A frame would probably be the best approach to solving this problem.

框架可能是解决此问题的最佳方法。

回答by Arthur Yip

Like Quentin said, you can use descendent selector to limit the scope. Something like lesscan help a lot. For example, I would like to have "bootstrap.css" applies only to #MyDiv, in "my.less":

正如 Quentin 所说,您可以使用后代选择器来限制范围。少之类的东西可以提供很多帮助。例如,我想让“bootstrap.css”仅适用于“my.less”中的#MyDiv:

#MyDiv {
  @import "bootstrap.less";
}

"bootstrap.css" should be renamed (or linked) to "bootstrap.less". Run:

“bootstrap.css”应重命名(或链接)为“bootstrap.less”。跑:

lessc my.less my.css

would add #MyDiv to every selectors in the imported file.

会将 #MyDiv 添加到导入文件中的每个选择器。

回答by Slavik Meltser

For one of my projects, I needed exactly the same thing, but to be also supported in CSS version 2.
After a long search all over the web, I didn't found anything useful, so I decided to created this functionality using JavaScript that can actually able to apply a whole css to a specific Element in DOM.

对于我的一个项目,我需要完全相同的东西,但要在 CSS 版本 2 中也得到支持。
在网上长时间搜索后,我没有找到任何有用的东西,所以我决定使用 JavaScript 创建这个功能实际上可以将整个 css 应用于 DOM 中的特定元素。

Just call the function applyCSSFileToElement, as described below (depended on jQuery library):

只需调用函数 applyCSSFileToElement,如下所述(取决于 jQuery 库):

function renderCSSForSelector(css, selector) {
    return ((css+"")||"").replace(/\n|\t/g, " ")
      .replace(/\s+/g, " ")
      .replace(/\s*\/\*.*?\*\/\s*/g, " ")
      .replace(/(^|\})(.*?)(\{)/g, function(
var cssFile = document.createElement( "link" );
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFIle.href = "file.css";
document.getElementsByTagName( "head" )[0].appendChild( cssFile );
, , , ) { var collector = [], parts = .split(","); for (var i in parts) { collector.push(selector + " " + parts[i].replace(/^\s*|\s*$/, "")); } return + " " + collector.join(", ") + " " + ; }); } function applyCSSToElement(css, elementSelector) { $("head").append("<style type=\"text/css\">" + renderCSSForSelector(css, elementSelector) + "</style>"); } function applyCSSFileToElement(cssUrl, elementSelector, callbackSuccess, callbackError) { callbackSuccess = callbackSuccess || function(){}; callbackError = callbackError || function(){}; $.ajax({ url: cssUrl, dataType: "text/css", success: function(data) { applyCSSToElement(data, elementSelector); callbackSuccess(); }, error: function(jqXHR) { callbackError(); } }) }

Functions explanations:

功能说明:

  • renderCSSForSelector- Actually prepends a selector for each style definition.
  • applyCSSToElement- Takes the CSS source data, applies renderCSSForSelector and injects it into the HEAD tag.
  • applyCSSFileToElement- Applies a CSS file (cssUrl) into a specific area (elementSelector) in DOM. The callbackSuccessis called when the file is loaded successfully and the CSS has been applied. The callbackErroris called when there is an error loading the CSS file.
  • renderCSSForSelector- 实际上为每个样式定义添加了一个选择器。
  • applyCSSToElement- 获取 CSS 源数据,应用 renderCSSForSelector 并将其注入 HEAD 标记。
  • applyCSSFileToElement- 将 CSS 文件 ( cssUrl) 应用到DOM 中的特定区域 ( elementSelector)。当文件加载成功并应用 CSS 时,将调用 callbackSuccess。该callbackError当有一个错误加载CSS文件被调用。

Good luck!

祝你好运!

回答by Will

You could use an iframe to load the preview page or dynamically load the CSS into the page. But, if you want the styles to only by applied to the div, you have to prefix your CSS selectors with the id of the div. #div-id #element-inside-div { }.

您可以使用 iframe 加载预览页面或将 CSS 动态加载到页面中。但是,如果您只想将样式应用于 div,则必须在 CSS 选择器前加上 div 的 id。#div-id #element-inside-div { }.

The script for loading it in might look something like this:

加载它的脚本可能如下所示:

##代码##