我想在我的网页中创建一种横幅,以 YouTube 视频作为背景,该横幅应从一侧到另一侧占据整个 iframe(拉伸视频并丢失一些片段就可以了)。像
background-size: cover;
之类的东西就可以了。我尝试过 this 但在我的情况下它并没有真正起作用(我只能看到一小段视频),可能是因为我的 iframe 的格式有点极端。
<header id="banner">
<div class="overlay">
<iframe src="https://www.youtube.com/embed/N9Y86YCRRDg?&autoplay=1&loop=1&playlist=N9Y86YCRRDg&rel=0&controls=0&mute=1" width="100%" height="315"></iframe>
</div>
</header>
这可以在 codepen 中使用您提供的示例,尽管某些片段在视频中被剪辑(帧效果);
html
<div class="video-background">
<div class="video-foreground">
<iframe src="https://www.youtube.com/embed/N9Y86YCRRDg?&autoplay=1&loop=1&playlist=N9Y86YCRRDg&rel=0&controls=0&mute=1" frameborder="0" allowfullscreen></iframe>
</div>
</div>
CSS
* { box-sizing: border-box; }
.video-background {
background: #000;
position: fixed;
top: 0; right: 0; bottom: 0; left: 0;
z-index: -99;
}
.video-foreground,
.video-background iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
@media (min-aspect-ratio: 16/9) {
.video-foreground { height: 300%; top: -100%; }
}
@media (max-aspect-ratio: 16/9) {
.video-foreground { width: 300%; left: -100%; }
}
@media all and (max-width: 600px) {
.vid-info { width: 50%; padding: .5rem; }
.vid-info h1 { margin-bottom: .2rem; }
}
@media all and (max-width: 500px) {
.vid-info .acronym { display: none; }
}
如果您需要将 iFrame 设置得太小并且红色播放按钮变得太大,您还可以按照将 iframe 缩放到父级的方法。
React 示例代码
const IFrame = () => {
const [scaleFactor, setScaleFactor] = useState(1);
const iFrameRef = useRef<HTMLIFrameElement>(null);
useEffect(() => {
const handleResize = () => {
const parentWidth = iFrameRef.current?.parentElement?.offsetWidth!;
const iFrameW = parseFloat(iFrameRef.current?.width!);
setScaleFactor(parentWidth / iFrameW);
};
window.addEventListener("resize", handleResize);
handleResize(); // Call once on initial render
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return (
<div
style={{
border: "0px",
position: "absolute",
top: "50.5%",
left: "80%",
width: "16%",
}}
>
<iframe
ref={iFrameRef}
className=""
width={1280/4}
height={720/4}
src="https://www.youtube.com/embed/aqyUoU0U4BA?autoplay=0&mute=0&controls=1&loop=1&showinfo=0&rel=0&modestbranding=1"
allow="autoplay; fullscreen"
allowFullScreen
style={{
transform: `scale(${scaleFactor})`,
transformOrigin: "top left",
}}
></iframe>
</div>
);
}
export default IFrame;