创建自定义节点以扩展 HTMLIFrameElement
Creating custom node to extend HTMLIFrameElement
是否可以创建自定义元素,如:“”,并且这个新元素将具有 iframe 元素的所有功能? (它自己的 document/window 对象等等...)?
扩展 <iframe>
要扩展标准 HTML 元素,您必须在 customElements.define()
方法中使用 { extends: "element" }
:
class MyFrame extends HTMLIFrameElement {
constructor () {
super()
console.log( 'created')
}
}
customElements.define( 'my-frame', MyFrame, { extends: 'iframe' } )
然后使用is="custom-element"
属性创建扩展元素:
<iframe is='my-frame'></iframe>
然后您可以将其用作标准 <iframe>
并添加您的自定义功能。
定义新的 HTML 标签
或者,如果您想要一个新的标签名称,请创建一个自主自定义元素(派生自 HTMLElement
),其中包含标准 <iframe>
元素:
class NewFrame extends HTMLElement {
constructor() {
super()
console.log( 'created' )
this.attachShadow( { mode: 'open' } )
.innerHTML = "<iframe></iframe>"
}
connectedCallback() {
setTimeout( () =>
this.shadowRoot.querySelector( 'iframe' ).contentDocument.body.innerHTML = this.innerHTML
)
}
}
customElements.define( 'new-frame', NewFrame )
在此示例中,自定义元素将使用 <new-frame>
的内容填充 <iframe>
文档。
<new-frame>Hello world !</new-frame>
此解决方案的缺点是您的新元素不会充当 <iframe>
。您必须为要转发到 <iframe>
内部的所有功能定义一些自定义方法。
是否可以创建自定义元素,如:“”,并且这个新元素将具有 iframe 元素的所有功能? (它自己的 document/window 对象等等...)?
扩展 <iframe>
要扩展标准 HTML 元素,您必须在 customElements.define()
方法中使用 { extends: "element" }
:
class MyFrame extends HTMLIFrameElement {
constructor () {
super()
console.log( 'created')
}
}
customElements.define( 'my-frame', MyFrame, { extends: 'iframe' } )
然后使用is="custom-element"
属性创建扩展元素:
<iframe is='my-frame'></iframe>
然后您可以将其用作标准 <iframe>
并添加您的自定义功能。
定义新的 HTML 标签
或者,如果您想要一个新的标签名称,请创建一个自主自定义元素(派生自 HTMLElement
),其中包含标准 <iframe>
元素:
class NewFrame extends HTMLElement {
constructor() {
super()
console.log( 'created' )
this.attachShadow( { mode: 'open' } )
.innerHTML = "<iframe></iframe>"
}
connectedCallback() {
setTimeout( () =>
this.shadowRoot.querySelector( 'iframe' ).contentDocument.body.innerHTML = this.innerHTML
)
}
}
customElements.define( 'new-frame', NewFrame )
在此示例中,自定义元素将使用 <new-frame>
的内容填充 <iframe>
文档。
<new-frame>Hello world !</new-frame>
此解决方案的缺点是您的新元素不会充当 <iframe>
。您必须为要转发到 <iframe>
内部的所有功能定义一些自定义方法。