shadow dom一个最简单的例子

时间:2022-07-26
本文章向大家介绍shadow dom一个最简单的例子,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文资料来自stackoverflow:https://stackoverflow.com/questions/34119639/what-is-shadow-root/34119775#34119775

The Shadow DOM is simply saying that some part of the page, has its own DOM within it. Styles and scripting can be scoped within that element so what runs in it only executes in that boundary.

页面某部分拥有自己的DOM,以及对应的styles和script.

This is one of the primary pieces needed for Web Components to work. Which is a new technology allowing developers to build their own encapsulated components that developers can use just like any other HTML element.

是web Components能够工作的基石。

shadow dom这个概念的引入,是为了解决传统HTML技术的一个痛点:

The DOM tree inside a widget isn’t encapsulated from the rest of the page. This lack of encapsulation means your document stylesheet might accidentally apply to parts inside the widget; your JavaScript might accidentally modify parts inside the widget; your IDs might overlap with IDs inside the widget and so on.

https://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/

看个具体的例子:

<html>
<button>Hello, world!</button>
<script>
var host = document.querySelector('button');
var root = host.createShadowRoot();
root.textContent = 'こんにちは、影の世界!';
</script>
</html>

通过document.getElementById返回的元素的innerHTML仍然是原始dom的hello world: