有没有办法在没有document.registerElement()的情况下定义新的HTML元素?

时间:2017-07-10 15:35:27

标签: javascript html html5 api

在某些浏览器中,您可以使用真正不兼容的Document.registerElement() API定义具有自定义功能的新HTML元素等。有没有办法避免使用此API并创建与许多浏览器兼容的新HTML元素?

2 个答案:

答案 0 :(得分:2)

呃,是的。使用 DOM standard

document.createElement("element type")

您可以(但我不知道您为什么会这样做)使用它来创建非标准元素。之后,它们只是JavaScript对象,因此您可以像对待任何其他对象一样自定义它们。

  

在HTML文档中,Document.createElement()方法创建   由tagName指定的HTML元素,如果是tagName,则为 HTMLUnknownElement   不被认可。



// Causes an HTMLUnknownElement to be created
var e = document.createElement("custom");

// Supports basic element interface
e.innerHTML = "I'm in a new <custom> element.";

// But, is a JS object like any other and so customized
// as such:
e.custom = function(){
  alert("custom operation");
};

// Is an element node (although invalid), so can be inserted into the DOM
document.body.appendChild(e);

// But, has custom functions:
e.custom();




答案 1 :(得分:1)

现在不推荐使用Document.registerElement。试试这个:https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define

相关问题