You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义jQuery多图片上传预览代码以适配Bootstrap 4布局需求

改造jQuery图片预览脚本适配Bootstrap 4布局需求

我来帮你调整这个脚本,让它完美实现你要的Bootstrap 4缩略图布局效果——固定宽高、一行排列自动换行,还有左右内边距的要求都能满足~

完整改造代码

首先调整HTML结构,给图片容器加上Bootstrap的row类,利用它的网格系统实现自动换行:

<!-- 图片预览容器 -->
<div class="gallery row"></div>

<!-- 文件上传控件 -->
<input type="file" id="product_sub_images" multiple>

然后修改jQuery脚本,调整插入的图片结构,用Bootstrap的列组件包裹图片,同时添加上必要的样式类:

<script>
$(document).ready(function(){
  // 多图片预览函数
  var imagesPreview = function(input, placeToInsertImagePreview) {
    if (input.files) {
      var filesAmount = input.files.length;
      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();
        reader.onload = function(event) {
          // 用Bootstrap的col-auto列包裹图片,添加缩略图类和自定义样式类
          $($.parseHTML('<div class="col-auto mb-3"><img class="img-thumbnail custom-preview-img"></div>'))
            .find('img')
            .attr('src', event.target.result)
            .end()
            .appendTo(placeToInsertImagePreview);
        }
        reader.readAsDataURL(input.files[i]);
      }
    }
  };

  $('#product_sub_images').on('change', function() {
    // 清空之前的预览,避免重复添加
    $('div.gallery').empty();
    imagesPreview(this, 'div.gallery');
  });
});
</script>

最后添加自定义CSS,设置图片固定宽高和内边距:

/* 自定义预览图片样式 */
.custom-preview-img {
  width: 200px;
  height: 200px;
  object-fit: cover; /* 保持图片比例,避免拉伸变形 */
}

/* 设置列的左右内边距 */
.gallery .col-auto {
  padding-left: 10px;
  padding-right: 10px;
}

关键修改说明

  • Bootstrap网格适配:用row和col-auto组合,col-auto会根据内容宽度自动分配空间,当一行放不下时自动换行,完美满足你的换行需求。
  • 缩略图样式:添加img-thumbnail类直接复用Bootstrap的缩略图样式,自带边框和圆角效果。
  • 固定宽高与比例保持:通过custom-preview-img类设置200px的固定宽高,object-fit: cover确保图片不会被拉伸变形,裁剪居中显示。
  • 内边距设置:给col-auto设置左右10px内边距,实现图片之间的间隔。
  • 新增清空预览:在文件选择时清空之前的预览内容,避免重复添加图片。

这样改造后,你的图片预览就完全符合需求啦,而且和Bootstrap 4的风格保持一致~

内容的提问来源于stack exchange,提问作者Mokhtar Ghaleb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:32:30