我是 JS 新手,我正在嘗試創建動態網站并從中學習。然而,我很掙扎,因為我嘗試了多種代碼和試驗,但我總是有一個重復的視頻。
這是 HTML:
<div class="container" id="cnn">
</div>
這是JS代碼:
function enter() {
var video = document.createElement("video");
video.type = "video/mp4";
video.src = "../images/myMovie.mp4";
video.autoplay = true;
video.muted = true;
video.id = "vdd"
document.body.appendChild(video);
var step2 = false;
video.addEventListener("timeupdate", function(){
// current time is given in seconds
if(this.currentTime >= 1) {
// pause the playback
this.pause();
this.remove();
step2 = true;
if (step2 == true){
document.getElementById("cnn").style.display = "inline"
console.log("Test 1");
const x = document.createElement("video");
const brr = document.createElement("div");
x.type = "video/mkv";
x.src = "../images/space.mkv";
x.autoplay = true;
x.muted = true;
x.id = "vdd1"
brr.appendChild(x);
// add the newly created element and its content into the DOM
const currentDiv = document.getElementById("cnn");
currentDiv.appendChild(brr);
}
}
});
}
uj5u.com熱心網友回復:
在向該節點添加新元素之前,請從該節點中洗掉子元素
const currentDiv = document.getElementById("cnn");
currentDiv.innerHTML = "";
currentDiv.appendChild(brr);
uj5u.com熱心網友回復:
嘗試直接訪問元素以將其洗掉,而不是參考“this”,而是從 DOM 中查詢它并像那樣洗掉它。您可以通過
document.getElementById("vdd").remove();
除非我誤解了重復的視頻,如果第二個視頻有問題,您永遠不會將 div 附加到檔案,您只會將新視頻附加到 div 元素,因此該元素不會顯示。
如果我誤解了您的問題,請告訴我。:)
uj5u.com熱心網友回復:
您正在創建多個<video>. video.addEventListener("timeupdate", function () { })在第一個video被有效洗掉之前被多次呼叫。
我建議反轉step2標志的使用,以確保 step2 只執行一次。
var video = document.createElement("video");
video.type = "video/mp4";
video.src =
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4";
video.autoplay = true;
video.muted = true;
video.id = "vdd";
document.body.appendChild(video);
var step2 = false;
video.addEventListener("timeupdate", function () {
// current time is given in seconds
if (this.currentTime >= 1) {
// pause the playback
this.pause();
this.remove();
if (step2 === false) { // <-- SEE HERE
step2 = true; // <-- SEE HERE
document.getElementById("cnn").style.display = "inline";
console.log("Test 1");
const x = document.createElement("video");
const brr = document.createElement("div");
x.type = "video/mp4";
x.src =
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4";
x.autoplay = true;
x.muted = true;
x.id = "vdd1";
brr.appendChild(x);
// add the newly created element and its content into the DOM
const currentDiv = document.getElementById("cnn");
currentDiv.appendChild(brr);
}
}
});
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div class="container" id="cnn"></div>
<script src="index.js"></script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318150.html
標籤:javascript 接口 dom 动态的
上一篇:科拉茲猜想
