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

多File Input拖拽上传时,如何仅高亮当前拖拽目标Div?

解决拖拽上传区域仅高亮最后一个目标的问题

看起来你遇到的核心问题有两个:一是重复的变量名覆盖了之前的事件绑定,二是事件处理时没有关联到当前触发事件的上传区域。下面一步步帮你解决:

问题根源分析

  1. 重复ID与变量覆盖:你的HTML里两个input用了同一个id="exampleInputFile"(这是HTML语法错误,ID必须唯一),而且两个脚本里的$fileInput和$droparea变量名完全重复,后面的脚本会直接覆盖前面的,导致只有最后一个上传区域的事件绑定生效。
  2. 全局选择器无关联:每个脚本里都用了全局的类选择器绑定事件,没有把输入框和它对应的拖拽区域关联起来,所以无法区分当前操作的是哪个区域。

修复方案

第一步:修正HTML(修复重复ID+添加通用类)

先把重复的ID改成唯一值,同时给所有拖拽区域加一个通用类file-drop-zone,方便统一处理:

<div class="col-sm-4">
 <label for="file_before">File Before</label>
 <div class="file-drop-area border file-drop-zone">
 <input type="file" id="file_before" class="file_before files" name="file_before[]" multiple required>
 <p class="message" name="drag">Drag your files here or click in this area.</p>
 </div>
 <div class="file_before_append"></div>
</div>
<div class="col-sm-4">
 <div class="form-group">
 <label for="file_after">File After</label>
 <div class="file_after-drop-area border file-drop-zone">
 <input type="file" id="file_after" class="file_after files" name="file_after[]" multiple required>
 <p class="message">Drag your files here or click in this area.</p>
 </div>
 <div class="file_after_append"></div>
 </div>
</div>

第二步:简化CSS(复用通用类样式)

把两个拖拽区域的is-active样式合并,减少重复代码:

form input.files{
 position: absolute;
 margin: 0;
 padding: 0;
 width: 100%;
 opacity: 0;
}
.border{
 border: 2px dashed #d2d6de;
 height: 40px;
}
form .message{
 width: 100%;
 height: 100%;
 text-align: center;
 line-height: 35px;
 overflow: hidden;
 color: #d2d6de;
}
label.col-sm-10 {
 padding-left: initial;
}
/* 通用拖拽区域样式 */
.file-drop-zone {
 position: relative;
 display: flex;
 width: 450px;
 max-width: 100%;
 transition: 0.2s;
}
/* 通用激活状态样式 */
.file-drop-zone.border.is-active {
 border: 2px dashed black;
}
/* 保留原有类兼容(可选,若不需要可删除) */
.file-drop-area, .file_after-drop-area {
 position: relative;
 display: flex;
 width: 450px;
 max-width: 100%;
 transition: 0.2s;
}

第三步:统一JS事件处理(关联当前区域)

合并两个脚本,用相对选择器找到当前输入框对应的拖拽区域,同时处理dragleave的冒泡问题(避免鼠标移到区域内子元素时错误移除样式):

<script>
// 给所有文件输入框绑定事件
$('.files').on('dragenter focus click', function() {
  // 找到当前输入框的父级拖拽区域
  $(this).closest('.file-drop-zone').addClass('is-active');
});

// 处理离开/失焦/放下事件
$('.files').on('dragleave blur drop', function(e) {
  const $dropZone = $(this).closest('.file-drop-zone');
  // 处理dragleave的特殊情况:只有鼠标真正离开整个区域才移除样式
  if (e.type === 'dragleave') {
    if (!$dropZone.has(e.relatedTarget).length) {
      $dropZone.removeClass('is-active');
    }
  } else {
    $dropZone.removeClass('is-active');
  }
});
</script>

关键修改点说明

  • 唯一ID:修正了HTML中重复的ID,符合HTML规范,同时让label能正确关联对应的输入框。
  • 相对选择器:用$(this).closest('.file-drop-zone')精准定位当前操作的拖拽区域,确保每个输入框的事件只影响自己对应的区域。
  • 冒泡处理:针对dragleave事件,通过检查relatedTarget判断鼠标是否真的离开了整个拖拽区域,避免误触发样式移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 09:32:48