12

我得到了一个外部样式表(.css 文件),它可能不会以任何方式改变。但是,我需要将此样式表应用于单个 div,因此需要将 div 的内容应用于我已经存在的网页中。我目前正在将样式表的内容作为文本读取到我需要影响的 div 中的空白样式标记(使用 .innerHTML)中,但这仍然会影响整个网页,而不仅仅是单个 div。有人可以帮忙吗?

4

8 回答 8

12

IFRAME 解决方案的工作原理如下:

在您的主 HTML 文件中,您将拥有 DIV:

<div id="myspecialdiv">
    <iframe width="100%" height="100%" frameborder="0" src="divcontent.html"></iframe>
</div>

根据需要设置样式。divcontent.html 文件应该是一个完整的 HTML 文件,包括 DIV 标记的内容,以及使用您的外部样式表的 LINK:

<html>
    <head>
        <link rel="stylesheet" href="path/to/external/stylesheet.css" />
    </head>
    <body>
        <!-- The contents of your DIV -->
    </body>
</html>
于 2013-05-03T10:53:10.547 回答
6

如果您可以使用 HTML5,您可以尝试使用scoped styles。您可以在 div 中包含 CSS,使其仅影响其父级:

<div>
    <style scoped>
        // Styles here
    </style>
</div>
于 2013-05-03T10:42:19.380 回答
3

这将对您有很大帮助:

http://css-tricks.com/saving-the-day-with-scoped-css/

仅将样式应用于某个定界的 escope。祝你好运!

恕我直言,比 iframe 解决方案更好..

相关:将外部 css 的范围限制为仅特定元素?

于 2014-12-02T11:19:05.800 回答
1

I suggest you can leave the external style sheet as it is and create an internal style sheet with the classes that you want from the external stylesheet to affect your single div and just rename it and apply those renamed classes to the div. The renaming is because the attributes of those classes may affect elements already existing on the page from external stylesheets.

<style>
.xxx {...} /* The renamed class from this internal css that should apply to your div */
</style>

Hope this helps.

于 2013-05-03T10:47:52.250 回答
1

如果您可以访问服务器端脚本(例如:PHP),您可以创建一个脚本来加载外部样式表,并在每个条目的前面附加一个类名。然后将此类应用于您的 DIV 标签。因此,如果 CSS 包括:

p { font-size: 12px; }

您将其修改为:

.mydiv p { font-size: 12px; }

并将您的 DIV 格式化为

<div class="mydiv">...</div>

然后,您将脚本作为样式表加载,而不是直接加载外部样式表。

<link rel="stylesheet" href="path/to/internal/script.php" />
于 2013-05-03T10:59:44.630 回答
0

我假设外部文件中的样式规范不包含在类或 ID 中,但它们是对标签的全面调整<p>(因此它不能包含在您的页眉中)。将您的 div 包含在<style scoped>标签中并在那里导入 .css 文件。请参阅:http ://css-tricks.com/saving-the-day-with-scoped-css/

于 2013-05-03T10:43:48.293 回答
0

您可以分配一个 CSS 前缀来定位您想要设置样式的文档部分。

于 2013-05-03T10:45:19.380 回答
0

scoped是个好主意,但存在浏览器兼容问题。

我通过在 css 文件中的所有选择器之前添加 pre-class 来解决这个问题:

https://github.com/ericf/grunt-css-selectors

于 2016-07-25T06:33:28.880 回答