如何实现Modal复用figcaption内容?移动端模态框优化需求
实现图片说明内容复用,避免重复编写
嘿,这个需求太接地气了——大量图片重复写说明内容不仅费时间,后期维护还容易出错。咱们可以借助Bootstrap模态框的事件机制,用JavaScript动态复用figcaption的内容,不用重复码字。下面是具体的实现方案:
核心思路
- 把图片说明只写一次在
figcaption标签里,通过CSS控制不同设备的显示(桌面端直接显示,移动端隐藏) - 移动端点击触发模态框时,用JavaScript自动抓取对应图片的
figcaption内容,填充到模态框中
修改后的代码
HTML部分
先把重复的figcaption删掉,只保留一处,同时调整触发模态框的链接结构:
<div class="col-5 col-sm-2 ml-auto aboutMid aboutMid1"> <figure class="cap-left"> <img src="http://www.classichits.ie/wp-content/uploads/2016/12/house.png" class="img-fluid"> <!-- 移动端触发按钮,不用包裹figcaption --> <a href="#myModal" role="button" data-toggle="modal" class="d-inline d-lg-none">查看说明</a> <!-- 仅桌面端显示的图片说明 --> <figcaption class="d-none d-lg-inline">The house is a converted farm building featuring traditional wooden shutters and terracotta roof tiles</figcaption> </figure> </div> <div class="col-5 col-sm-2 mr-auto mr-sm-0 aboutMid aboutMid1"> <figure class="cap-left"> <img src="assets/about/about2.jpg" class="img-fluid"> <a href="#myModal" role="button" data-toggle="modal" class="d-inline d-lg-none">查看说明</a> <figcaption class="d-none d-lg-inline">The large garden features breathtaking views of the valley and Puilaurens Castle</figcaption> </figure> </div> <!-- 通用模态框,不用每个图片单独创建 --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="myModalLabel">图片说明</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- 这里的内容会被JavaScript动态填充 --> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div>
JavaScript部分(依赖jQuery,因为Bootstrap模态框需要)
利用Bootstrap的show.bs.modal事件,在模态框显示前自动填充内容:
// 监听模态框即将显示的事件 $(document).on('show.bs.modal', '#myModal', function(event) { // 获取触发模态框的按钮 const triggerBtn = $(event.relatedTarget); // 找到按钮所在的figure,再获取里面的figcaption文本 const captionText = triggerBtn.closest('figure').find('figcaption').text().trim(); // 填充到模态框的body中 $(this).find('.modal-body').text(captionText); });
额外优化建议
如果需要保留figcaption里的HTML格式(比如加粗、换行),可以把代码里的.text()改成.html(),这样连样式也能完整复用。
内容的提问来源于stack exchange,提问作者DoeysGac
相关产品推荐
相关产品推荐

