Dynamically create a HTML5 video element without it being shown in the page

前端 未结 3 764
感动是毒
感动是毒 2021-02-05 07:23

Is it possible to dynamically create a HTML5 video element so that I can access the element by API\'s like document.getElementById or Name but it may not show up in

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 07:33

    Sure you can create everything just using JS. You need nothing to be pre-created in html body.

    Here is simple way of creating video element in JS:

    var videlem = document.createElement("video");
    /// ... some setup like poster image, size, position etc. goes here...
    /// now, add sources:
    var sourceMP4 = document.createElement("source"); 
    sourceMP4.type = "video/mp4";
    sourceMP4.src = "path-to-video-file.mp4";
    videlem.appendChild(sourceMP4);
    //// same approach add ogg/ogv and webm sources
    

    Before doing this, you should check if browser supports video element, and if so, which file formats can be played. This you can do by:

    var supportsVideoElement = !!document.createElement('video').canPlayType;
    

    Then, if video element is supported, test which video formats can be played:

    var temp = document.createElement('video');
    var canPlay_MP4 = temp.canPlayType('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
    var canPlay_OGV = temp.canPlayType('video/ogg; codecs="theora,vorbis"');
    var canPlay_WEMB = temp.canPlayType('video/webm; codecs="vp8,vorbis"');
    

    After this, you can add video element to your page using JS only, with proper video sources set. There may be an issue with .htaccess on server side where you need to add lines:

    AddType video/ogg .ogv
    AddType video/ogg .ogg
    AddType video/mp4 .mp4
    AddType video/webm .webm
    

    This may not be needed, depending on how your server is set, but if you encounter issue with playing videos from your server, but they play fine from eg. localhost on your dev machine, this can solve the issue. .htaccess with above lines should be placed in the folder where video files are located, on server side.

    Ok now, in order to have this element available with getElementById(...), you just need to set id of it, when you create it:

    var videlem = document.createElement("video");
    videlem.id = "xxxxxx";
    

    And now you can later find it using:

    var videlem = document.getElementById("xxxxxx");
    

    However, as someone commented already, you don't need to do this if you have already created the element and have variable pointing to it... just use it directly.

    Hope this helps :-)

提交回复
热议问题