有人可以帮我重写以下代码,使其在不使用ID的情况下正常工作,以便我可以在单个页面上将其用于多个视频吗?预先谢谢你!
JAVASCRIPT (WORKS FOR SINGLE VIDEO)
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var pauseIcon = document.getElementById("pauseIcon");
var playIcon = document.getElementById("playIcon");
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
pauseIcon.style.visibility ="visible";
playIcon.style.visibility ="hidden";
} else {
video.pause();
pauseIcon.style.visibility ="hidden";
playIcon.style.visibility ="visible";
}
});
}
Here is a link to my current working CodePen as well:
https://codepen.io/jhughes1006/pen/yZPVGo
{{1}}
答案 0 :(得分:2)
您可以将class
替换为每个id
,并使用.querySelectorAll()
执行相同的任务。
onload = e => {
const containers = document.querySelectorAll('.video-container'):
containers.forEach(container => {
const video = container.querySelector('video');
const playButton = container.querySelector('button');
playButton.addEventListener('click', e => {
// do stuff
})
})
}
答案 1 :(得分:0)
供其他人将来参考,这是基于@ guest271314给出的答案的多个视频的新工作代码。
onload = function onload(e) {
var containers = document.querySelectorAll(".video-container");
containers.forEach(function(container) {
var video = container.querySelector("video");
var playButton = container.querySelector("button");
var pauseIcon = container.querySelector(".pause-icon");
var playIcon = container.querySelector(".play-icon");
playButton.addEventListener("click", function(e) {
if (video.paused == true) {
video.play();
pauseIcon.style.visibility ="visible";
playIcon.style.visibility ="hidden";
} else {
video.pause();
pauseIcon.style.visibility ="hidden";
playIcon.style.visibility ="visible";
}
});
});
};