how to protect embedded div style not to be overridden by website style

两盒软妹~` 提交于 2019-12-08 05:22:33

问题


I have div with its own style. I embedded this div on other website.

<div id="scoped-div">
  <style>
    label {
      color: green;
    }
  </style>

  <label> Scoped div </label>
</div>

But I face problem, my div style is overridden by website style. I don't want to use iframe. Except for the use of iframe is there any other way to protect my div style by external style changes?


回答1:


Your request is exactly what Shadow DOM makes possible:

  1. attach a Shadow DOM to the element you want to protect (here: #scope-div),
  2. put the HTML code you want to protect in the Shadow DOM,
  3. clone it from a <template> element to get it easy (optional).

That's it!

var div = document.querySelector( "#scoped-div" )
var template = document.querySelector( "template" )

var sh
if ( 'attachShadow' in div )
  sh = div.attachShadow( { mode: "closed" } )  //Shadow DOM v1
else
  sh = div.createShadowRoot()                 //Shadow DOM v0 fallback

sh.appendChild( template.content.cloneNode( true ) )
<template>
  <style>
    label {
      color: green;
    }
  </style>

  <label> Scoped div </label>
</template>

<div id="scoped-div">
</div>



回答2:


There is no way to fully protect your styles. But you can try the following:

  • Try to specify your elements selectors as specific as possible (e.g. with attributes and IDs)
  • Use inline styles
  • Use !important (but be careful with a broad use of importants)


来源:https://stackoverflow.com/questions/38916842/how-to-protect-embedded-div-style-not-to-be-overridden-by-website-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!