为何鼠标悬停时视频与基础图片间存在微小间隙?
问题
为图片实现了鼠标悬停效果:悬停时播放循环视频并显示文本覆盖层,但视频略小于基础图片,悬停时两者间出现微小间隙。已给视频及文本覆盖层的CSS设置width:100%,仍无法解决。代码编写于CARGO.site平台,{Image 4}替代常规HTML img标签,相关代码如下:
相关代码
JavaScript
$(document).ready(function() { $('.video-1').each(function(el) { var _this = $(this); _this.on('mouseover', function(ev) { _this[0].src += "&autoplay=1"; ev.preventDefault(); }); }); });
CSS
#video-1 { display: block; width: 100%; height: 100%; fit-content: inherit; } .container-1 { position: relative; width: 100%; margin-bottom: 5px; } .image-1 { display: block; width: 100%; height: inherit; } .overlay-img-1 { position: absolute; top: 0%; bottom: 0; left: 0; right: 0; height: 98.5%; width: 100%; opacity: 0; transition: .5s ease; background-color: rgba(0, 0, 0, 0.4); } .overlay-img-1:hover { opacity: 1; } .text-1 { width: 100%; color: white; font-size: 20px; position: absolute; top: 60%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; }
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container-1" gid="13"> <a href="https://racerpictures.cargo.site/easy-life-beeswax" class="image-link-1"> <div class="image-1" gid="1"> <div class="overlay-img-1"> <video id="video-1" autoplay="" loop="" class=""> <source src="https://files.cargocollective.com/c1549988/A002_C018_0922BW_002.mp4" type="video/mp4"> </video> <div class="text-1"> <h4>EASY LIFE | BEESWAX<br></h4> <p class="caption-small-1">MUSIC VIDEO</p> </div> </div> <div class="base-img-1"> {image 4} </div> </div> </a> </div>
解决方案与排查思路
修正覆盖层高度硬编码
.overlay-img-1设置的height:98.5%是直接导致间隙的原因,改成height:100%,配合top:0; bottom:0确保覆盖层完全填满容器:.overlay-img-1 { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; /* 替换98.5% */ width: 100%; opacity: 0; transition: .5s ease; background-color: rgba(0, 0, 0, 0.4); }清除视频默认边距并优化适配
浏览器可能给video标签加默认边距,同时替换fit-content为object-fit: cover确保视频按比例填满容器:#video-1 { display: block; width: 100%; height: 100%; object-fit: cover; margin: 0; padding: 0; border: none; }覆盖平台默认图片样式
CARGO.site可能给{Image 4}生成的img标签加了额外样式,强制清除:.base-img-1 img { display: block; width: 100%; height: auto; margin: 0; padding: 0; border: none; }修正JS选择器不匹配问题
原JS用.video-1类选择器,但video标签只有video-1id,没有对应类,同时避免重复添加autoplay参数:$(document).ready(function() { $('#video-1').on('mouseover', function(ev) { if (!this.src.includes('autoplay=1')) { this.src += "&autoplay=1"; } ev.preventDefault(); }); // 可选:鼠标移出暂停视频优化体验 $('#video-1').on('mouseout', function() { this.pause(); }); });
内容的提问来源于stack exchange,提问作者Lxxj
相关产品推荐
相关产品推荐

