1 回答

TA貢獻1801條經驗 獲得超8個贊
這是我的工作版本你的片段。我只創建了一次DOM結構,每個視頻下都有所有必要的按鈕。我在開始時使所有按鈕都不可見(),并且我還只添加了一次事件監聽器。事件偵聽器是通用的。附加到父 div 時,它將觸發不同的操作,具體取決于所覆蓋的元素:display:none
#videos
如果是“BUTTON”,則該按鈕的文本內容用于“開始”或“暫停”相關視頻。
在“VIDEO”的情況下,通過將樣式屬性“顯示”設置為“內聯”來顯示關聯的按鈕。
請注意,我還刪除了按鈕中的ID。這些不是唯一的,因此不是不正確的HTML。
window.onload = init;
function init() {
document.querySelectorAll('.video').forEach(v=>{
v.closest('div').innerHTML+=`<br><span class="buttons">
<button>play</button>
<button>pause</button>
<button>volume up</button>
<button>volume down</button>
<button>mute</button></span>`;
});
document.querySelector('#videos').addEventListener('click',function(ev){var el=ev.target;
if (el.tagName=="BUTTON"){var func=el.textContent
if (["play","pause"].indexOf(func)>-1) el.closest('div').children[0][func]()
} else if (el.tagName=="VIDEO") {
document.querySelectorAll('span.buttons').forEach(b=>b.style.display='none');
el.parentNode.querySelector('span.buttons').style.display='inline';
}
})
}
span.buttons {display:none}
<div id="videos">
<div id="video1">
<video class="video" >
<source src="https://www.videvo.net/videvo_files/converted/2018_04/preview/180301_06_A_CityRoam_03.mp420186.webm">
</video>
</div>
<div id="video2">
<video class="video" >
<source src="https://www.videvo.net/videvo_files/converted/2016_01/preview/Forest_15_2_Videvo.mov92730.webm">
</video>
</div>
<div id="video3">
<video class="video">
<source src="https://www.videvo.net/videvo_files/converted/2016_09/preview/160820_125_NYC_OutOfFocusCarLights5_1080p.mp444096.webm">
</video>
</div>
</div>
添加回答
舉報