我们做外贸独立站时,主页或其它介绍页有可能会需要弹出视频并播放,背景图可以随时替换。有些模板会写好这些代码,如果 Wordpress 的页面构建器没有这个功能,购买的模板也没有,那么我们就要创建布局,并且自己添加背景图可点击弹出层播放 Youtube 视频的代码。
以下分享这块的完整前端代码,有一点点小不足,一伙会讲明:
加入CSS样式:
.container-video {
display: flex;
}
.video-background {
width: 476px;
height: 506px;
background-image: url("https://替换为你背景图片的地址");
background-size: cover;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
@media (max-width: 1100px) {
.video-background {
width: 320px;
height: 300px;
background-size: cover;
background-position: center;
}
}
@media (max-width: 768px) {
.container-video {
display: flex;
justify-content: center;
}
.video-background {
width: 300px;
height: 300px;
background-size: cover;
background-position: center;
}
}
.play-icon {
width: 0;
height: 0;
border-top: 15px solid transparent;
border-bottom: 15px solid transparent;
border-left: 25px solid white;
position: relative;
cursor: pointer;
z-index: 2;
}
.play-icon::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
border-radius: 50%;
border: 2px solid white;
background: rgba(0, 0, 0, 0);
z-index: 1;
transform: translate(-80%, -50%);
}
.video-popup {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9999;
}
.video-popup.open {
display: block;
opacity: 1;
}
.video-content {
width: 60%;
height: 70%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 1%;
box-sizing: border-box;
}
@media (max-width: 768px) {
.video-content {
width: 90%;
height: auto;
padding: 10px;
}
}
iframe {
width: 100%;
height: 100%;
}
.close-btn {
font-size: 24px;
position: absolute;
top: 20px;
right: 20px;
cursor: pointer;
z-index: 10000;
color: #fff;
}
显示背景图的代码:
<div class="container-video">
<div class="video-column">
<div class="video-background" onclick="openVideoPopup('这里填入Youtube视频地址ID')">
<div class="play-icon"></div>
</div>
</div>
</div>
<div id="videoPopup" class="video-popup">
<div class="video-content">
<span class="close-btn" onclick="closeVideoPopup()">×</span>
<iframe id="youtubeVideo" width="853" height="480" src="" frameborder="0" allowfullscreen></iframe>
</div>
</div>
script 代码,加入页尾 /body 前:
<script>
function openVideoPopup(videoId) {
var popup = document.getElementById('videoPopup');
popup.classList.add('open');
setTimeout(function() {
var embedUrl = 'https://www.youtube.com/embed/' + videoId;
document.getElementById('youtubeVideo').src = embedUrl;
}, 300); // 等待300毫秒确保CSS动画完成
}
function closeVideoPopup() {
var popup = document.getElementById('videoPopup');
popup.classList.remove('open');
setTimeout(function() {
document.getElementById('youtubeVideo').src = '';
}, 300); // 等待CSS动画完成
}
</script>
PC端添加代码背景图效果如下:
PC端点击背景图播放按钮后弹出层效果:
上面弹出层会在页面最上层,覆盖其它元素,页面上下滚动位置不变。右上角可关闭层,有适配移动端,手机效果差不多,不足的地方就是移动端样式,没有自适应,而是根据不同屏幕宽度,会改变背景图的大小,懂 CSS 的可自行修改,能做到完美自适应的话可发我代码替换。
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。

还木有评论哦,快来抢沙发吧~