Ответ:
Вот готовое решение для открытия модального окна с YouTube видео по клику на кнопку:
<button id="play" data-source="https://www.youtube.com/embed/dQw4w9WgXcQ">Play</button>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<iframe id="youtube-video" width="560" height="315" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
}
.modal.show {
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
position: relative;
background-color: #fefefe;
padding: 20px;
border-radius: 8px;
max-width: 800px;
width: 90%;
}
.close {
position: absolute;
top: 10px;
right: 20px;
font-size: 28px;
font-weight: bold;
color: #aaa;
cursor: pointer;
}
.close:hover {
color: #000;
}
iframe {
width: 100%;
aspect-ratio: 16/9;
}
</style>
<script>
const playButton = document.getElementById('play');
const modal = document.getElementById('modal');
const closeButton = document.querySelector('.close');
const iframe = document.getElementById('youtube-video');
playButton.addEventListener('click', () => {
const videoUrl = playButton.getAttribute('data-source');
iframe.src = videoUrl + '?autoplay=1';
modal.classList.add('show');
});
closeButton.addEventListener('click', () => {
modal.classList.remove('show');
iframe.src = '';
});
// Закрытие модального окна при клике вне его
window.addEventListener('click', (event) => {
if (event.target === modal) {
modal.classList.remove('show');
iframe.src = '';
}
});
</script>
Этот код включает:
- Кнопку Play с атрибутом data-source, содержащим ссылку на YouTube видео
- Модальное окно с iframe для встраивания видео
- Стили для:
- Затемненного фона
- Центрированного модального окна
- Кнопки закрытия
- Адаптивного видео (сохраняет соотношение сторон 16:9)
- JavaScript для:
- Открытия модального окна по клику
- Вставки видео в iframe с автовоспроизведением
- Закрытия модального окна
- Остановки видео при закрытии
Вы можете изменить ссылку в data-source на нужное вам YouTube видео. Для получения embed-ссылки на YouTube нажмите "Поделиться" → "Встроить" и скопируйте URL из атрибута src iframe.