使用getElementBy一次控制一个元素



我试图让用户点击播放按钮,观看案例研究视频,并让视频回到其原始状态一旦完成播放。问题是,当在一个页面上添加多个案例研究时,getElementById()不仅是无效的HTML,而且还播放错误的案例研究视频或根本不会播放。

我在网上看到getElementsByNamegetElementsByClassName可能是另一种选择,但我不能让它们工作。

案例研究HTML块(在页面上重复)

<div class="caseStudy">
<button id="playButton"></button>
<div id="casestudyPoster" class="caseStudy_poster"></div>

<iframe class="caseStudy_video" src="<vimeo-url-here>" width="100%" height="100%" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>
</div>

JavaScript:

var poster = document.getElementById("casestudyPoster");
var button = document.getElementById("playButton");

poster.onclick = function() { fadeImage() };
button.onclick = function() { fadeImage() };
function fadeImage() {
poster.style.visibility = "hidden";
button.style.visibility = "hidden";
var iframe = document.querySelector('iframe');
var player = new Vimeo.Player(iframe);
player.play();

player.on('ended', function(data){
poster.style.visibility = "visible";
button.style.visibility = "visible";
});

}

我怎么能让这个JavaScript工作与多个caseStudys?

问题是您只将JavaScript功能绑定到一个元素,而您希望将JavaScript功能绑定到多个元素。

下面是A)收集几个相似的元素B)将唯一事件绑定到它们的唯一属性的例子。

// Gather all your similar elements
const videoElements = document.querySelectorAll( '.video-element' );
// For each element, let's do something with it.
videoElements.forEach( ( vidEl ) => {
// For this current element, lets create useful variables from elements found within it.
const playButton = vidEl.querySelector( '.play-button' );
const dynamicText = vidEl.querySelector( '.dynamic-text' );

// For this current element's play button, let's bind a unique event to it.
playButton.onclick = () => { dynamicText.innerHTML = `Video Playing!` };
} );
.video-element {
border: 1px solid;
margin: 1rem;
}
<div class="video-element">
<h2>Video 1</h2>
<button class="play-button">Play</button>
<span class="dynamic-text">I have my own functionality!</span>
</div>
<div class="video-element">
<h2>Video 2</h2>
<button class="play-button">Play</button>
<span class="dynamic-text">I have my own functionality!</span>
</div>
<div class="video-element">
<h2>Video 3</h2>
<button class="play-button">Play</button>
<span class="dynamic-text">I have my own functionality!</span>
</div>
<div class="video-element">
<h2>Video 4</h2>
<button class="play-button">Play</button>
<span class="dynamic-text">I have my own functionality!</span>
</div>

相关内容

  • 没有找到相关文章

最新更新