如何在文档中嵌入作用域html(css) [英] How to embed a scoped html (css) in a document

查看:46
本文介绍了如何在文档中嵌入作用域html(css)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够将从远程api获取的HTML代码片段(嵌套元素和CSS)嵌入到我的文档中,以使它们的CSS不会影响我的整个文档.

I need to be able to embed HTML snippets (nested elements and CSS) fetched from a remote api inside my document, in a way that their CSS won't affect on my whole document.

我需要获取(随机)gmail邮件HTML,并将其嵌入到我的网站中.事实是,大多数消息都有其CSS标记来设置消息html的样式.问题是这些CSS中有一些与我自己的文档CSS混为一谈.我该如何在CSS中嵌入html代码段,使其具有自己的作用域而不与外部内容进行交互?

I need to fetch (random) gmail messages HTMLs and embed them in my website. The thing is that most messages have their CSS tags to style the message html. The problem is that some of these CSS mess up with my own document CSS. How can I embed an html snippet with CSS, in a way that it will have its own scope and not interact with what's outside of it?

<html>
<body>
<h1>Your gmail messages</h1>
<div id="gmail-message">
  <!-- Here to be injected automatically. Changing classes, etc is not possible -->
  <h1>This a gmail message</h1>
  <style type="text/css">
  h1 {
  color: red;
  }
  </style>
</div>
</body>
</html>

gmail-message div之外的h1标签也会受到影响,因此为红色.
我该怎么办才能解决这个问题?

The h1 tag outside the gmail-message div is also affected and is therefore red.
What do I need to do to get around this?

推荐答案

我找到了解决方案.

首先,在某个位置插入一个空的iframe广告代码.

First, insert an empty iframe tag somewhere.

<iframe id="iframeTag" src="about:blank"></iframe>

第二,通过以下方式将html代码段加载到该iframe中:

Second, load the html snippet into that iframe, the following way:

var doc = document.getElementById('iframeTag').contentWindow.document;
doc.open();
doc.write(<html_snippet>);
doc.close();

这样,< html_snippet> 的CSS不会与外部文档的CSS混淆.

This way the <html_snippet>'s css won't mix up with the outer document's.

这篇关于如何在文档中嵌入作用域html(css)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆