问题
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:
- attach a Shadow DOM to the element you want to protect (here:
#scope-div
), - put the HTML code you want to protect in the Shadow DOM,
- 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