Element.attachShadow()
method attaches a shadow DOM tree to the specified element and returns a reference to its
ShadowRoot
.
Note that you can't attach a shadow root to every type of element. There are some that can't have a shadow DOM for security reasons (for example
<a>
), and more besides. The following is a list of elements you
can
attach a shadow root to:
<article>
<aside>
<blockquote>
<body>
<div>
<footer>
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<header>
<main>
<nav>
<p>
<section>
<span>
var shadowroot = element.attachShadow(shadowRootInit);
shadowRootInit
ShadowRootInit
dictionary, which can contain the following fields:
mode
A string specifying the encapsulation mode for the shadow DOM tree. This can be one of:
open
: Elements of the shadow root are accessible from JavaScript outside the root, for example using
Element.shadowRoot
:
element.shadowRoot; // Returns a ShadowRoot obj
closed
: Denies access to the node(s) of a closed shadow root from JavaScript outside it:
element.shadowRoot; // Returns null
delegatesFocus
true
, specifies behavior that mitigates custom element issues around focusability. When a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available
:focus
styling.
返回
ShadowRoot
对象。
| 异常 | 解释 |
|---|---|
InvalidStateError
|
The element you are trying to attach to is already a shadow host. |
NotSupportedError
|
You are trying to attach a shadow root to an element outside the HTML namespace, or the element cannot have a shadow attached to it (see above). |
The following example is taken from our
word-count-web-component
demo (
see it live also
). You can see that we use
attachShadow()
in the middle of the code to create a shadow root, which we then attach our custom element's contents to.
// Create a class for the element
class WordCount extends HTMLParagraphElement {
constructor() {
// Always call super first in constructor
super();
// count words in element's parent element
var wcParent = this.parentNode;
function countWords(node){
var text = node.innerText || node.textContent
return text.trim().split(/\s+/g).length;
}
var count = 'Words: ' + countWords(wcParent);
// Create a shadow root
var shadow = this.attachShadow({mode: 'open'});
// Create text node and add word count to it
var text = document.createElement('span');
text.textContent = count;
// Append it to the shadow root
shadow.appendChild(text);
// Update count when element content changes
setInterval(function() {
var count = 'Words: ' + countWords(wcParent);
text.textContent = count;
}, 200)
}
}
// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
The definition of 'attachShadow()' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
attachShadow
|
Chrome 53 | Edge 79 |
Firefox
63
|
IE No | Opera 40 | Safari 10 | WebView Android 53 | Chrome Android 53 |
Firefox Android
63
|
Opera Android 41 | Safari iOS 10 | Samsung Internet Android 6.0 |
delegatesFocus
option of
ShadowRootInit
字典。
非标
|
Chrome Yes | Edge 79 | Firefox No | IE No | Opera ? | Safari ? | WebView Android Yes | Chrome Android Yes | Firefox Android No | Opera Android ? | Safari iOS ? | Samsung Internet Android Yes |
完整支持
不支持
兼容性未知
实验。期望将来行为有所改变。
非标。预期跨浏览器支持较差。
用户必须明确启用此特征。
元素
accessKey
属性
childElementCount
children
classList
className
clientHeight
clientLeft
clientTop
clientWidth
currentStyle
firstElementChild
id
innerHTML
lastElementChild
localName
名称
namespaceURI
nextElementSibling
onfullscreenchange
onfullscreenerror
openOrClosedShadowRoot
outerHTML
part
prefix
previousElementSibling
runtimeStyle
scrollHeight
scrollLeft
scrollLeftMax
scrollTop
scrollTopMax
scrollWidth
shadowRoot
slot
tabStop
tagName
after()
animate()
append()
attachShadow()
before()
closest()
computedStyleMap()
createShadowRoot()
getAnimations()
getAttribute()
getAttributeNames()
getAttributeNode()
getAttributeNodeNS()
getAttributeNS()
getBoundingClientRect()
getClientRects()
getElementsByClassName()
getElementsByTagName()
getElementsByTagNameNS()
hasAttribute()
hasAttributeNS()
hasAttributes()
hasPointerCapture()
insertAdjacentElement()
insertAdjacentHTML()
insertAdjacentText()
matches()
msZoomTo()
prepend()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
releasePointerCapture()
remove()
removeAttribute()
removeAttributeNode()
removeAttributeNS()
replaceChildren()
replaceWith()
requestFullscreen()
requestPointerLock()
scroll()
scrollBy()
scrollIntoView()
scrollIntoViewIfNeeded()
scrollTo()
setAttribute()
setAttributeNode()
setAttributeNodeNS()
setAttributeNS()
setCapture()
setPointerCapture()
toggleAttribute()
afterscriptexecute
auxclick
blur
click
compositionend
compositionstart
compositionupdate
contextmenu
copy
cut
dblclick
DOMActivate
DOMMouseScroll
error
focus
focusin
focusout
fullscreenchange
fullscreenerror
gesturechange
gestureend
gesturestart
keydown
keypress
keyup
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
mousewheel
MozMousePixelScroll
msContentZoom
MSGestureChange
MSGestureEnd
MSGestureHold
MSGestureStart
MSGestureTap
MSInertiaStart
MSManipulationStateChanged
overflow
paste
scroll
select
show
touchcancel
touchend
touchmove
touchstart
underflow
webkitmouseforcechanged
webkitmouseforcedown
webkitmouseforceup
webkitmouseforcewillbegin
wheel