文章里放视频,最省事的做法往往是错的。
三种方式
直链 <video>
自己上传的 mp4,用原生 <video controls> 最稳,没有第三方脚本,也不会被墙。
B 站 iframe
player.bilibili.com 的播放器重量适中,缺点是要处理弹幕和外链限制。
YouTube iframe
国内访问不稳定,通常只作为补充。
站内的写法
后台写作时直接用这三种标记,服务端会展开成对应的 iframe / video:
<div class="video-embed"><iframe src="//player.bilibili.com/player.html?bvid=BV1xx411c7mD&autoplay=0" title="嵌入式视频" loading="lazy" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
<div class="video-embed"><iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="嵌入式视频" loading="lazy" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
<div class="video-embed"><video controls preload="metadata" src="/static/uploads/videos/demo.mp4"></video></div>
渲染时统一包在 .video-embed 里,保证宽高比不会把版心撑破:
.video-embed { position: relative; padding-top: 56.25%; }
.video-embed iframe { position: absolute; inset: 0; width: 100%; height: 100%; }
结论
- 自己的视频走直链;
- 需要引用的外部内容才用 iframe;
- 永远不要让嵌入内容决定页面宽度。