如何根据CSS类调整Magnific Popup弹窗尺寸?
实现Magnific Popup竖版与方形弹窗切换效果
需求说明
现有基于Magnific Popup的图片画廊,需通过CSS类区分,实现竖版(portrait)和方形(square)两种弹窗尺寸效果。
步骤1:修改HTML结构,添加区分类
给需要不同弹窗效果的图片链接添加自定义类,比如popup-portrait或popup-square:
<div class="container-fluid"> <div class="row container-grid mt-5 projects-wrapper"> <div class="img-max-width marketing"> <div class="item-box"> <!-- 竖版弹窗 --> <a class="cbox-gallary1 mfp-image popup-portrait" href="images/portfolio/work-8.jpg" title="Project Name"> <img class="item-container mfp-fade" src="images/portfolio/work-8.jpg" alt="2" /> <div class="item-mask"> <div class="item-caption"> <h5 class="text-dark">竖版项目</h5> <p class="text-muted">client: Kay Garland</p> </div> </div> </a> <!-- 方形弹窗 --> <a class="cbox-gallary1 mfp-image popup-square" href="images/portfolio/work-square.jpg" title="Square Project"> <img class="item-container mfp-fade" src="images/portfolio/work-square.jpg" alt="Square" /> <div class="item-mask"> <div class="item-caption"> <h5 class="text-dark">方形项目</h5> <p class="text-muted">client: Kay Garland</p> </div> </div> </a> </div> </div>
步骤2:调整Magnific Popup初始化配置
针对不同类分别初始化弹窗,绑定对应的自定义样式类:
Larix.prototype.initMagnificPopup = function() { // 通用图片弹窗基础配置 const basePopupConfig = { type: 'image', closeOnContentClick: true, gallery: { enabled: true, navigateByImgClick: true, preload: [0, 1] } }; // 竖版弹窗初始化 $('.mfp-image.popup-portrait').magnificPopup({ ...basePopupConfig, mainClass: 'mfp-fade popup-portrait' }); // 方形弹窗初始化 $('.mfp-image.popup-square').magnificPopup({ ...basePopupConfig, mainClass: 'mfp-fade popup-square' }); // 保留原有视频弹窗配置 $('.mfp-video').magnificPopup({ disableOn: 700, type: 'iframe', mainClass: 'mfp-fade', removalDelay: 160, preloader: false, fixedContentPos: false }); };
步骤3:添加CSS样式控制弹窗尺寸
通过自定义类修改弹窗容器及图片的尺寸限制:
/* 竖版弹窗样式:优先限制高度,宽度自适应比例 */ .popup-portrait .mfp-img { max-height: 90vh; max-width: calc(100vw - 40px); } .popup-portrait .mfp-image-holder { display: flex; align-items: center; justify-content: center; min-height: 100vh; } /* 方形弹窗样式:限制宽高一致,保持方形比例 */ .popup-square .mfp-img { max-width: 70vh; max-height: 70vh; object-fit: contain; } .popup-square .mfp-image-holder { display: flex; align-items: center; justify-content: center; min-height: 100vh; } /* 保留原有关闭按钮样式 */ .mfp-image-holder .mfp-close, .mfp-iframe-holder .mfp-close { color: white; right: -6px; text-align: right; padding-right: 6px; width: 100%; }
内容的提问来源于stack exchange,提问作者erics15
相关产品推荐
相关产品推荐

