为什么可以用new Image 而不能用new Div 或者new Span?
Why can you use new Image but not new Div or new Span?
在示例中,我看到 new Image()
创建一个新的 HTML 图像元素,但是当我尝试 new Div()
时,没有任何支持。是否有此或未来任何计划添加它的原因?
示例:
var image = new Image();
var div = new Div(); // error
为什么存在这种方法,这是一个很好的问题。 HTML 生活标准没有回答这个问题 (https://html.spec.whatwg.org/multipage/embedded-content.html#dom-image)。它只是说明除了工厂方法之外还提供了 HTMLImageElements 的构造函数
document.createElement('img')
使用此函数,您可以创建所有 DOM 个元素,例如
document.createElement('div')
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
这些构造函数是否会为我不知道的其他元素实现。
Div
class 不存在。可以使用函数 Document.createElement()
:
创建任何 DOM 元素
var div = document.createElement('div');
var img = document.createElement('img');
document.createElement('div')
创建一个新的 HTMLDivElement
.
new Image()
creates in fact an HTMLImageElement
等同于 document.createElement('img')
.
图像可以使用 new Image()
syntax for historical reasons. Back in the 90s, the Image
object has been one of the first dynamic HTML feature implemented by all browsers before the current DOM 甚至被发明出来(更不用说所有浏览器都以相同的方式实现)。
我的 Google 搜索结果表明您正在使用 Web Api
也可能是构造函数的存在:
- HTMLImageElement 的构造函数为 Image(),因此它允许 new Image()
- HTMLDivElement 没有构造函数
来源:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement
https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement
在示例中,我看到 new Image()
创建一个新的 HTML 图像元素,但是当我尝试 new Div()
时,没有任何支持。是否有此或未来任何计划添加它的原因?
示例:
var image = new Image();
var div = new Div(); // error
为什么存在这种方法,这是一个很好的问题。 HTML 生活标准没有回答这个问题 (https://html.spec.whatwg.org/multipage/embedded-content.html#dom-image)。它只是说明除了工厂方法之外还提供了 HTMLImageElements 的构造函数
document.createElement('img')
使用此函数,您可以创建所有 DOM 个元素,例如
document.createElement('div')
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
这些构造函数是否会为我不知道的其他元素实现。
Div
class 不存在。可以使用函数 Document.createElement()
:
var div = document.createElement('div');
var img = document.createElement('img');
document.createElement('div')
创建一个新的 HTMLDivElement
.
new Image()
creates in fact an HTMLImageElement
等同于 document.createElement('img')
.
图像可以使用 new Image()
syntax for historical reasons. Back in the 90s, the Image
object has been one of the first dynamic HTML feature implemented by all browsers before the current DOM 甚至被发明出来(更不用说所有浏览器都以相同的方式实现)。
我的 Google 搜索结果表明您正在使用 Web Api
也可能是构造函数的存在:
- HTMLImageElement 的构造函数为 Image(),因此它允许 new Image()
- HTMLDivElement 没有构造函数
来源:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement