css - Youtube 视频作为特定部分的背景
问题描述
我需要制作一个 youtube 视频作为特定部分而不是整个页面的背景。所以我需要部分是 390px 高度和 100% 宽度。
现在我正在使用此代码,但问题是 youtube iframe 是 100% 全宽,但视频本身非常小并且带有黑色边栏。这是代码:
<div class="video-wrapper">
<div id="player"></div>
</div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '100%',
videoId: 'EhArkyWXpO0',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
我正在使用 youtube API 并在 javascript 中设置 100% 宽度。我很确定我必须使用 css 来实现这一点,但到目前为止还没有成功......
我想要的输出是没有黑色边栏的wideo
谢谢!
解决方案
您需要使用 javascript 通过设置width
窗口或父节点的宽度来调整宽度。
将父节点的大小设置为 100% 并尝试以下操作:
node = document.getElementById("player");
player = new YT.Player('player', {
height: node.parentNode.offsetWidth * 9 / 16,
width: node.parentNode.offsetWidth,
videoId: 'EhArkyWXpO0',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
)
如果要在调整窗口大小时调整大小,则必须添加一个函数window.onresize
:
window.onresize = function() {
var node = document.getElementById('player');
// fetch player; may a childnode of node[id="player"]
player.setAttribute("width", node.parentNode.offsetWidth);
};
推荐阅读
- jpa - Spring Data JPA 批量插入
- sql-server - 循环时从sql获取数据到datagridview?
- python - 使用多处理实现排序的生产者/消费者队列
- mysql - Laravel 可通知 - 向选定用户发送通知
- html - Thymeleaf th:每个仅在下拉菜单中显示第一个元素
- simulation - 试图制作一个简单的二维 2 体轨道模拟器,但一切都在飞向太空?
- firebase-cloud-messaging - FCM 是否支持 iOS 13 的新 apns-push-type
- c - 这是递归互斥锁的合适用例吗?
- xml - 对于每个 XML 节点
在 我怎样才能得到文本值 使用 Groovy - list - 如何将两个列表的元素一起添加到 Scheme 中的单个列表中?