是的,可以做到。
我可以使用createElement() 方法创建我想要的source 元素,然后使用appendChild() 方法将它们附加到video 元素。
所以,我将修改我发布的original fiddle 中的JS 代码,以创建一个带有JS 的video 元素,该元素将具有:
- 两个来源:
- 在原始小提琴中的两个视频上定义的所有功能:
本质上,一个类似于我的 video 元素的元素,有两个来源,使用 HTML 创建并在问题中定义:
<video controls autoplay loop muted>
<source src=".../foo.ogv" type="video/ogg"/>
<source src=".../foo.mp4" type="video/mp4"/>
</video>
修改视频元素
我继续修改创建的video 元素,丢弃src 属性,但保留我定义的所有其余属性:
/* Video element creation */
this.video = document.createElement("video");
/* Video element properties settings */
this.video.controls = true;
this.video.autoplay = true;
this.video.loop = true;
this.video.muted = true;
创建源元素并将它们附加到视频元素
要添加源,我使用createElement() 方法创建source 元素,然后设置源将具有的属性,最后使用appendChild() 方法将源元素附加到@987654337 @ 元素。在这里,我为 OGV 文件创建了源元素。
/* First source element creation */
this.source1 = document.createElement("source");
/* Attribute settings for my first source */
this.source1.setAttribute("src", ".../foo.ogv");
this.source1.setAttribute("type", "video/ogg");
/* Append the first source element to the video element */
this.video.appendChild(this.source1);
我可以添加多个来源,所以对于这个问题,由于我想添加两个来源,一个 OGV 文件和一个 MP4 文件,我将两者都添加。我继续为第二个创建source 元素。
/* Second source element creation */
this.source2 = document.createElement("source");
/* Attribute settings for my second source */
this.source2.setAttribute("src", ".../foo.mp4");
this.source2.setAttribute("type", "video/mp4");
/* Append the second source element to the video element */
this.video.appendChild(this.source2);
将视频元素附加到正文
当我完成将源元素添加到我的video 元素后,唯一要做的就是将视频元素附加到带有appendChild() 的HTML 正文:
document.body.appendChild(this.video);
最终代码
对于回答代码,我将首先放置 video 元素和两个来源,使用 HTML 创建并在问题中定义,以进行比较。我添加了一个<hr> 中断,只是出于美观的原因。
HTML(正文)
<video controls autoplay loop muted>
<source src="http://techslides.com/demos/sample-videos/small.ogv" type="video/ogg" />
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4" />
</video>
<hr/>
<!--
As the video element created with JS is appended to the body,
it will be located here, at the end of that body.
-->
JavaScript
function Main() {
this.video = document.createElement("video");
this.video.controls = true;
this.video.autoplay = true;
this.video.loop = true;
this.video.muted = true;
this.source1 = document.createElement("source");
this.source1.setAttribute("src",
"http://techslides.com/demos/sample-videos/small.ogv");
this.source1.setAttribute("type", "video/ogg");
this.video.appendChild(this.source1);
this.source2 = document.createElement("source");
this.source2.setAttribute("src",
"http://techslides.com/demos/sample-videos/small.mp4");
this.source2.setAttribute("type", "video/mp4");
this.video.appendChild(this.source2);
document.body.appendChild(this.video);
}
var main = new Main();
小提琴
在this new fiddle 你可以看到所有的代码。