我正在创建一个新的视频元素,然后想要在视频开始加载时显示一个微调器,直到它获得第一帧然后删除该元素。以下是我的代码 -
var videoElem, src;
videoElem = document.createElement("video");
videoElem.src = src;
var preloader = '<div class="preloader-wrapper"><div class="spinner-layer"><div class="circle-clipper left"><div class="circle"></div></div>' + '<div class="gap-patch"><div class="circle"></div></div><div class="circle-clipper right"><div class="circle"></div></div></div></div>';
//renders when video has started loading - show preloader
videoElem.addEventListener("loadstart", function () {
console.log("Video has started loading...!");
//jQuery(preloader).insertBefore(videoElem); //works fine but I don't know how to delete the preloader in the loadeddata eventlistener
videoElem.appendChild(preloader);
});
//renders when is loaded - delete preloader
videoElem.addEventListener("loadeddata", function () {
console.log("Video has loaded successfully!");
videoElem.removeChild(preloader);
});
appendChild
和removeChild
无效。给出错误:
未捕获TypeError:无法在'Node'上执行'removeChild':参数1在HTMLVideoElement.eval中不是'Node'类型
答案 0 :(得分:0)
您需要将字符串解析为HTML Node
,以便将其附加到另一个HTML Nodes
。
您可以使用DOMParser:
执行此操作var preloader = new DOMParser().parseFromString('<div class="preloader-wrapper"><div class="spinner-layer"><div class="circle-clipper left"><div class="circle"></div></div>' + '<div class="gap-patch"><div class="circle"></div></div><div class="circle-clipper right"><div class="circle"></div></div></div></div>', 'text/html');
答案 1 :(得分:0)
我有解决方案。我试图使用removeChild(preloader)
。这里的Preloader返回整个html元素。因此,通过id删除它解决了我的问题。此外,在视频标签内添加预加载器元素是错误的方法,并且不会显示加载器。为此,我获取了主div元素的id,然后添加/删除了预加载器,如下所示 -
var videoLoader = '<div id="videoLoader" class="preloader-wrapper"><div class="spinner-layer"><div class="circle-clipper left"><div class="circle"></div></div>' + '<div class="gap-patch"><div class="circle"></div></div><div class="circle-clipper right"><div class="circle"></div></div></div></div>';
var parentDiv = document.getElementById('parentDiv');
parentDiv.insertAdjacentHTML('afterbegin',videoLoader); // add in loadstart listener
parentDiv.removeChild(document.getElementById('videoLoader')); //add in loadeddata listener
元素的输出如下 -
<div id="parentDiv">
<div id="videoLoader">..preloader..</div>
<video>...</video>
</div>