CSS - 将div中的元素与全局页面样式隔离,就像它是iFrame一样?

时间:2016-02-04 22:51:37

标签: javascript html css angularjs sharepoint

是否可以将div中的元素隔离,就像它在iFrame中一样?

我在SharePoint中有一个应用程序,它全部都是从我想要完全关闭的全局SharePoint样式中获取的,所以我的应用程序只使用它包含的css。

EG:假设页面有一个全局样式表。假设我在该页面上放了一个div,它有自己的嵌入式CSS。我可以以某种方式完全忽略全局样式表吗?

https://plnkr.co/edit/2H2TJJz6rNZK18OK6VLW?p=preview

<html>
<head>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <h1>Global parent element - red</h1>

  <div class="self-contained-css">

    <style type="text/css">
      h1 {
        color:red;
        border: 1px solid blue;
      }
    </style>

    <h1>Self contained css element - blue</h1>
    <p>Self contained css should behave as if it was inside an iFrame. This is to isolate from SharePoint css ultimately.</p>
  </div>

</body>
</html>

4 个答案:

答案 0 :(得分:1)

Web组件将是您与iframe类似的封装的唯一选择。您可以使用webcomponents.js

等填充物获得相当好的覆盖率

Polymer是一个使Web组件更容易的好框架。

这会使你的代码看起来像这样:

... HTML here that uses your global styles ...
<my-element></my-element> <!-- this element would not inherit the global CSS -->

在您的my-element组件内(这只是您导入页面的文件系统中的另一个文件 - 请参阅上面的文档),您可以在my-element的内容中包含唯一的样式。 / p>

答案 1 :(得分:0)

问题是你的全局样式中有一个!important声明。虽然我通常不建议这样做,但您必须将其添加到您的声明中才能覆盖它们。即。

&#13;
&#13;
/* Global parent styles go here */

h1 {
  color:red;
  border: 5px solid red !important;
}

h1 {
        color:red;
        border: 1px solid blue !important;
      }
&#13;
<body>
  
  <h1>Global parent element - red</h1>
  
  <div class="self-contained-css">
    
    <style type="text/css">
      h1 {
        color:red;
        border: 1px solid blue !important;
      }
    </style>
    
    <h1>Self contained css element - blue</h1>
    <p>Self contained css should behave as if it was inside an iFrame. This is to isolate from SharePoint css ultimately.</p>
  </div>
  
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在我的情况下使用阴影dom我使用角度1所以我使用iframe但在角度2我们可以玩阴影dom

答案 3 :(得分:0)

使用将srcdoc属性设置为html的iFrame。

var myIframe = document.createElement('iframe');
myIframe.src = 'about:blank';
var info = `<html>
<head>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <h1>Global parent element - red</h1>

  <div class="self-contained-css">

    <style type="text/css">
      h1 {
        color:red;
        border: 1px solid blue;
      }
    </style>

    <h1>Self contained css element - blue</h1>
    <p>Self contained css should behave as if it was inside an iFrame. This is to isolate from SharePoint css ultimately.</p>
  </div>

</body>
</html>`;
myIframe.srcdoc = info;
var body = window.document.querySelector('body');
body.insertBefore(myIframe, body.firstChild);

我需要动态注入我的html内容,而不受页面css的影响,所以这就是为什么我的iframe是用js创建的,但不应该是因为你的html只能用html编写的原因。尽管srcdoc可能有点混乱,但将它(srcdoc)编写为js变量然后附加它可能更清晰。