【问题标题】:Shorthand for extending native DOM element?扩展本机 DOM 元素的简写?
【发布时间】:2017-05-07 00:36:01
【问题描述】:

作为explained in mdn,自定义元素可能基于原生元素。例如,<button is="my-button">。我正在寻找的是一种相反的语法。我想要创建一个元素的简写,该元素的标签是自定义的并且基于本机元素,例如<purchase-button is="button">。我不打算在 HTMLButtonElement 提供的内容上向这个自定义元素添加功能。只是名字。

然而,这不起作用:

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

结果元素不扩展HTMLButtonElemenet

【问题讨论】:

    标签: javascript dom web-component shadow-dom custom-element


    【解决方案1】:

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

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

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

    作为一种解决方法,定义一个<purchase-button> 自定义元素,您可以在其中插入<button>。然后可以使用带有<slot> 元素的Shadow DOM 来反映<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 )
    &lt;purchase-button id=PB&gt;Pay&lt;/purchase-button&gt;

    【讨论】:

      【解决方案2】:

      这是一种丑陋的方式:

      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>"))
      &lt;button&gt;Purchase&lt;/button&gt; ⬅ native &amp;lt;button&amp;gt;&lt;p&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-03
        • 2014-02-14
        • 1970-01-01
        • 2017-05-04
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多