Shorthand 用于扩展原生 DOM 元素?

Shorthand for extending native DOM element?

explained in mdn一样,自定义元素可能基于原生元素。例如,<button is="my-button">。我正在寻找的是一种相反的语法。我想要一个 shorthand 来创建一个标签是自定义的并且基于原生元素的元素,例如 <purchase-button is="button">。我并没有考虑在 HTMLButtonElement 提供的基础上向这个自定义元素添加功能。只是名字。

然而,这不起作用:

let purchaseButton = document.createElement('purchase-button', { is: 'button' })
document.body.appendChild(purchaseButton)

生成的元素未扩展 HTMLButtonElemenet

这是不可能的,自定义元素规范中不存在。

关于此要求,请参阅规范论坛中的 issue 603

有些人正在讨论其他问题中的类似需求(例如#509,祝阅读顺利...)。

作为变通方法,定义一个 <purchase-button> 自定义元素,并在其中插入 <button>。然后你可以使用阴影 DOM 和 <slot> 元素来反映 <purchase-button> 的原始内容。

customElements.define( 'purchase-button', class extends HTMLElement {
    constructor() {
        super()
        this.attachShadow( { mode: 'open' } )
            .innerHTML = '<button><slot></slot></button>'
    }
} )

PB.onclick = ev => 
  console.info( '[%s] clicked', ev.target.textContent )
<purchase-button id=PB>Pay</purchase-button>

这是一种丑陋的方式:

class PButton extends HTMLElement {}
customElements.define("purchase-button", PButton)
function PurchaseButton () {
    var pb = document.createElement('purchase-button')
    pb.__proto__ = PurchaseButton.prototype
    return pb
}
PurchaseButton.prototype.__proto__ = HTMLButtonElement.prototype
var purchaseButton = PurchaseButton()
purchaseButton.textContent = "Purchase"
purchaseButton.style = window.getComputedStyle(document.querySelector("button")).cssText
document.body.appendChild(purchaseButton)
document.body.appendChild(document.createTextNode(" ⬅ custom <purchase-button>"))
<button>Purchase</button> ⬅ native &lt;button&gt;<p>