看到这个fiddle。这是我的手表预告片按钮,第一个按钮工作得很好。但第二个观看预告片按钮不起作用。2个具有相同CSS和JS的按钮不起作用。
它有什么问题?
这里是我的代码:
HTML:
<button id="watchbutton">Watch Trailer ►</button>
<br>
<button id="watchbutton">Watch Trailer ►</button>
<div id="close">
<div id="trailerdivbox">
<div class="videoWrapper">
<iframe id="video" class="trailervideo" width="560" height="315" data-
src="https://www.youtube.com/embed/TDwJDRbSYbw" src="about:blank" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
CSS:
/* Watch Trailer Button CSS */
#watchbutton {
background-color: #f2f2f2;
color: red;
font-weight: 600;
border: none;
/* This one removes the border of button */
padding: 10px 12px;
}
#watchbutton:hover {
background-color: #e2e2e2;
cursor: pointer;
}
#trailerdivbox {
display: none;
width: 100%;
height: 100%;
position: fixed;
top:0%;
overflow: auto; /* Enable Scrolling */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
.videoWrapper {
position: relative;
padding-bottom: 56.25%;
/* 16:9 */
padding-top: 25px;
height: 0;
}
.videoWrapper iframe {
position: absolute;
max-width: 560px;
max-height: 315px;
width: 95%;
height: 95%;
left: 0;
right: 0;
margin: auto;
}
的Javascript
<script>
// Get the modal
var modal = document.getElementById('trailerdivbox');
// Get the button that opens the modal
var btn = document.getElementById("watchbutton");
function playVideo() {
var video = document.getElementById('video');
var src = video.dataset.src;
video.src = src + '?autoplay=1';
}
function resetVideo() {
var video = document.getElementById('video');
var src = video.src.replace('?autoplay=1', '');
video.src = '';
video.src = src;
}
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
playVideo();
}
var trailerbox = document.getElementById("close");
trailerbox.onclick = function() {
modal.style.display = "none";
resetVideo();
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
resetVideo();
}
}
</script>
我并不是说这是唯一的问题,但你的两个按钮都有相同的ID。这立即是你需要解决的**问题。ID的意思是与文档中的其他内容完全独立,这意味着**没有元素应该与另一个元素**共享一个ID。 – Frits
在修复与双ID的问题 - 由弗里茨,普拉萨德及其他提到的 - 你仍然需要告诉'playVideo'播放不同的视频,这取决于你按哪个按钮。参见[**我的回答下面**](https://stackoverflow.com/questions/44330728/2-buttons-with-same-css-and-js-are-not-working/44331691#44331691)的方式要做到这一点。 –