本文资料来自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:
要获取更多Jerry的原创文章,请关注公众号"汪子熙":
汪子熙 认证博客专家 前端框架 Node.js SAP JerryWang,2007年从电子科技大学计算机专业硕士毕业后加入SAP成都研究院工作至今。Jerry是SAP社区导师,SAP中国技术大使。2020年5月下旬,Jerry做了脑部肿瘤的开颅切除手术,对编程和人生又有了新的感悟。