如何保护嵌入式div样式不被网站样式覆盖 [英] how to protect embedded div style not to be overridden by website style

查看:71
本文介绍了如何保护嵌入式div样式不被网站样式覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的div具有自己的风格.我将此div嵌入到其他网站上.

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>

但是我遇到了问题,我的div样式被网站样式所覆盖.我不想使用iframe.除了使用iframe之外,还有其他方法可以通过外部样式更改来保护我的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?

推荐答案

您的请求正是 Shadow DOM 使得:

  1. 将Shadow DOM附加到要保护的元素上(此处: #scope-div),
  2. 将要保护的HTML代码放入Shadow DOM,
  3. <template>元素中克隆它以使其变得容易(可选).
  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).

就是这样!

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>

这篇关于如何保护嵌入式div样式不被网站样式覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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