嵌入 YouTube 视频
iframe 嵌入 YouTube、控制参数 autoplay/mute/loop
嵌入 YouTube 视频
用 <iframe> 嵌入 YouTube 视频到你的网页——只需复制粘贴。
学完本章你将: 掌握 iframe 嵌入 YouTube、控制参数。
基本嵌入
html
<iframe width="560" height="315"
src="https://www.youtube.com/embed/VIDEO_ID"
title="YouTube 视频播放器"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write;
encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
常用控制参数
在 URL 后面添加参数控制播放行为:
html
<!-- 自动播放 + 静音 -->
<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1&mute=1"></iframe>
<!-- 循环播放 -->
<iframe src="https://www.youtube.com/embed/VIDEO_ID?loop=1&playlist=VIDEO_ID"></iframe>
<!-- 隐藏播放器控件 -->
<iframe src="https://www.youtube.com/embed/VIDEO_ID?controls=0"></iframe>
<!-- 组合使用(用 & 分隔) -->
<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1&mute=1&loop=1&controls=0"></iframe>
| 参数 | 值 | 说明 |
|---|---|---|
| `autoplay` | 1 | 自动播放(需 mute) |
| `mute` | 1 | 静音 |
| `loop` | 1 | 循环(需 playlist) |
| `controls` | 0/1 | 控件显示/隐藏 |
| `start` | 秒数 | 从第几秒开始 |
响应式嵌入
html
<style>
.video-container {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
height: 0;
overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
}
</style>
<div class="video-container">
<iframe src="https://www.youtube.com/embed/VIDEO_ID"
frameborder="0" allowfullscreen></iframe>
</div>