You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

适配移动端的YouTube嵌入iframe响应式布局调整需求

解决方案:响应式YouTube视频iframe适配移动端

要让YouTube视频iframe在保持500px×281px比例的同时适配移动端,核心思路是用百分比内边距容器固定宽高比,再让iframe占满容器空间。具体实现如下:

1. 核心CSS样式

添加以下CSS,通过容器的padding-top维持精确宽高比(281/500=56.2%),同时让容器自适应父元素宽度:

/* 响应式视频容器 */
.youtube-container {
  position: relative;
  width: 100%;
  max-width: 500px; /* 限制PC端最大宽度为原尺寸 */
  padding-top: 56.2%; /* 281/500*100%,精确维持原比例 */
  overflow: hidden;
}

/* 让iframe占满容器 */
.youtube-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: none;
}

2. 调整JavaScript生成逻辑

修改生成iframe的代码,将每个iframe包裹在上述容器中,再插入到#videos div里:

<div id="videos"></div>

<script>
// 解析URL查询参数中的视频ID列表(假设参数名为videoIds,用逗号分隔)
const urlParams = new URLSearchParams(window.location.search);
const videoIds = urlParams.get('videoIds')?.split(',') || [];

const videosContainer = document.getElementById('videos');

videoIds.forEach(id => {
  // 创建容器
  const container = document.createElement('div');
  container.className = 'youtube-container';
  
  // 创建iframe
  const iframe = document.createElement('iframe');
  iframe.src = `https://www.youtube.com/embed/${id}`;
  iframe.title = 'YouTube video player';
  iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
  iframe.allowFullscreen = true;
  
  // 组装并插入DOM
  container.appendChild(iframe);
  videosContainer.appendChild(container);
});
</script>

效果说明

  • PC端:容器最大宽度限制为500px,和原尺寸一致,iframe保持500×281的比例
  • 移动端:容器宽度自动适配屏幕宽度,通过padding-top的百分比自动计算高度,完美维持原比例,不会出现溢出或缩放变形

内容的提问来源于stack exchange,提问作者user20319483

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:50:10