扩展原生DOM元素的简写?

时间:2016-12-21 14:35:35

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

作为explained in mdn,自定义元素可以基于本机元素。例如,cp。我正在寻找的是一种相反的语法。我想创建一个标签是自定义且基于本地元素的元素的简写,例如<button is="my-button">。我没有考虑在<purchase-button is="button">提供的内容上添加此自定义元素的功能。只是名字。

然而,这不起作用:

HTMLButtonElement

结果元素不会延伸let purchaseButton = document.createElement('purchase-button', { is: 'button' }) document.body.appendChild(purchaseButton)

2 个答案:

答案 0 :(得分:3)

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

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

有些人正在讨论其他问题的类似需求(例如#509,祝你好运......)。

要解决此问题,请定义protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null)) { if (isoStore.FileExists("contacts.dat")) { // We already have an old one, delete it isoStore.DeleteFile("contacts.dat"); } using (IsolatedStorageFileStream fs = isoStore.CreateFile("contacts.dat")) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, contacts); } } } 自定义元素,您可以在其中插入using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null)) { if (isoStore.FileExists("contacts.dat")) { IsolatedStorageFileStream fs = isoStore.OpenFile("contacts.dat", System.IO.FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); contacts = (List<Contact>) bf.Deserialize(fs); }else { // We don't have a backup file, create some dummy entries contacts = new List<Contact>(); contacts.Add(new Contact("John Smith", "1234567")); contacts.Add(new Contact("Emma Brown", "7654321")); } } MyDataGrid.ItemsSource = contacts; 。然后,您可以使用带有<purchase-button>元素的Shadow DOM来反映<button>的原始内容。

&#13;
&#13;
<slot>
&#13;
<purchase-button>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

这是一个丑陋的方式:

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>