实现文件选择后替换Label默认文本的jQuery技术问询
自定义文件上传按钮:选中文件后显示文件名
问题说明
需要美化文件上传控件,未选择文件时标签显示指定文本(如“Choisir le recto”),选择文件后标签显示文件名而非默认文本。
修正后的完整代码
HTML
<form method="POST" enctype="multipart/form-data"> <input type="file" name="recto" id="recto" class="btnsend" /> <label for="recto" class="labelbtn"><span> Choisir le Recto</span></label> <input type="file" name="verso" id="verso" class="btnsend" /> <label for="verso" class="labelbtn"><span>Choisir le Verso</span></label> <input type="file" name="selfie" id="selfie" class="btnsend" /> <label for="selfie" class="labelbtn"><span>Choisir le Selfie</span></label> <br> <input type="submit" name="submit" class="sendall"> </form>
CSS
.btnsend { display: block; visibility: hidden; position: absolute; } .labelbtn { color: #fff; display: inline-block; margin-bottom: 0; font-weight: normal; text-align: center; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; background-color: #0057a0; border: 1px solid transparent; white-space: nowrap; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none } .labelbtn:hover { opacity: 0.8; background-color: #0072a0; } .sendall { margin-top: 30px; }
jQuery 脚本
$('input[type=file]').change(function() { // 获取文件名,处理浏览器路径前缀问题 var filename = $(this).val().split('\\').pop(); // 获取当前input对应的label里的span元素 var targetSpan = $(this).next('label').find('span'); // 保存原始文本(仅第一次获取) if (!$(this).data('originalText')) { $(this).data('originalText', targetSpan.text().trim()); } // 根据是否选择文件设置文本 if (filename) { targetSpan.text(filename); } else { // 若取消选择,恢复原始文本 targetSpan.text($(this).data('originalText')); } });
关键修正点
- 选择器错误修复:原脚本中
$('span.' + idname).next().find('span')的选择逻辑完全错误,因为标签内的span并没有绑定对应input的id作为类。正确的方式是通过$(this).next('label')直接找到当前input相邻的标签,再定位到内部的span。 - 增加文本恢复逻辑:当用户打开文件选择框后取消选择时,标签会恢复到原始的提示文本,提升交互体验。
内容的提问来源于stack exchange,提问作者Kamil_Krm
相关产品推荐
相关产品推荐

