简体   繁体   English

为什么你可以使用新的图像而不是新的Div或新的Span?

[英]Why can you use new Image but not new Div or new Span?

In examples I've seen new Image() to create a new HTML image element but when I try new Div() there is no support. 在示例中,我看到了new Image()来创建一个新的HTML图像元素,但是当我尝试new Div() ,没有支持。 Is there a reason for this or any plan in the future to add it? 是否有理由在未来添加此计划或任何计划?

Example: 例:

var image = new Image();
var div = new Div(); // error

The Div class doesn't exist. Div类不存在。 Any DOM Element can be created using the function Document.createElement() : 可以使用Document.createElement()函数创建任何DOM元素:

var div = document.createElement('div');
var img = document.createElement('img');

document.createElement('div') creates a new HTMLDivElement . document.createElement('div')创建一个新的HTMLDivElement

new Image() creates in fact an HTMLImageElement and is equivalent to document.createElement('img') . new Image()实际上创建了一个HTMLImageElement ,相当于document.createElement('img')

Images can be created using the new Image() syntax for historical reasons. 出于历史原因,可以使用new Image()语法创建new Image() Back in the 90s, the Image object has been one of the first dynamic HTML feature implemented by all browsers before the current DOM was even invented (not to mention implemented the same way by all browsers). 早在90年代, Image对象就是当前DOM发明之前所有浏览器实现的第一个动态HTML功能之一(更不用说所有浏览器以相同的方式实现)。

It's a good question why that method exists. 这个方法存在的原因是一个很好的问题。 The HTML Living Standard doesn't answer that question ( https://html.spec.whatwg.org/multipage/embedded-content.html#dom-image ). HTML Living Standard没有回答这个问题( https://html.spec.whatwg.org/multipage/embedded-content.html#dom-image )。 It just states there is a constructor for HTMLImageElements provided in addition to the factory method document.createElement('img') 它只是声明除了工厂方法document.createElement('img')之外还提供了HTMLImageElements的构造函数。

With this function you can create all DOM elements, eg document.createElement('div') https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement 使用此函数,您可以创建所有DOM元素,例如document.createElement('div') https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

Whether these constructors will be implemented for other elements I don't know. 这些构造函数是否将用于我不知道的其他元素。

My Google search concluded that you are using Web Api 我的Google搜索结论是您正在使用Web Api

It may also be due to existence of constructor: 它也可能是由于构造函数的存在:

  1. HTMLImageElement has constructor as Image(), so it allows new Image() HTMLImageElement的构造函数为Image(),因此它允许新的Image()
  2. HTMLDivElement has no constructor HTMLDivElement没有构造函数

source: 资源:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM