为input file添加onchange后上传一次失效,样式参数重置问题求助
解决input file上传后自定义属性丢失的问题
问题分析
上传后input元素被系统(推测是SharePoint附件控件)重新渲染替换,导致自定义的size、title、style等属性全部丢失,页面刷新后才会恢复初始状态。
解决办法
方法1:上传完成后手动恢复属性
- 页面加载时保存初始属性值
// 放在script标签末尾或DOMContentLoaded事件中执行 const fileInput = document.getElementById('onetidIOFile'); const originalProps = { size: fileInput.size, title: fileInput.title, style: fileInput.getAttribute('style'), className: fileInput.className // 若用了CSS类也一并保存 };
- 修改
OkAttach函数,在上传完成后恢复属性
- 同步上传逻辑:直接在函数末尾添加恢复代码
function OkAttach() { // 你的原有上传逻辑代码... // 恢复自定义属性 const fileInput = document.getElementById('onetidIOFile'); fileInput.size = originalProps.size; fileInput.title = originalProps.title; fileInput.setAttribute('style', originalProps.style); fileInput.className = originalProps.className; // 清空文件值,保证下次选择同一文件能触发onchange事件 fileInput.value = ''; }
- 异步上传逻辑(如AJAX/fetch):在成功回调中执行恢复
function OkAttach() { const fileInput = document.getElementById('onetidIOFile'); const formData = new FormData(); formData.append('file', fileInput.files[0]); // 示例异步上传逻辑 fetch('/你的上传接口地址', { method: 'POST', body: formData }) .then(res => res.json()) .then(data => { // 上传成功后恢复属性 fileInput.size = originalProps.size; fileInput.title = originalProps.title; fileInput.setAttribute('style', originalProps.style); fileInput.className = originalProps.className; fileInput.value = ''; }) .catch(err => console.error('上传失败:', err)); }
方法2:监听DOM变化自动恢复属性
如果系统会直接替换input元素,用MutationObserver监听父元素,当新input被添加时自动重置属性:
const attachContainer = document.getElementById('attachmentsOnClient'); const fileInput = document.getElementById('onetidIOFile'); const originalProps = { size: fileInput.size, title: fileInput.title, style: fileInput.getAttribute('style'), className: fileInput.className }; const observer = new MutationObserver(mutations => { mutations.forEach(mutation => { if (mutation.addedNodes.length) { // 查找新生成的目标input元素 const newInput = attachContainer.querySelector('input[type="file"][id="onetidIOFile"]'); if (newInput) { // 恢复属性 newInput.size = originalProps.size; newInput.title = originalProps.title; newInput.setAttribute('style', originalProps.style); newInput.className = originalProps.className; // 重新绑定onchange事件 newInput.onchange = OkAttach; } } }); }); // 启动监听 observer.observe(attachContainer, { childList: true, subtree: true });
方法3:用CSS类替代内联style(更稳定)
把内联样式提取成CSS类,避免style属性丢失导致样式失效:
/* 放在页面style标签或外部CSS文件中 */ .custom-file-input { height: 100px; width: 420px; }
修改初始input代码,添加class:
<input type="file" name="fileupload0" onchange='OkAttach()' id="onetidIOFile" size="56" title="Drag files here or click to upload" class="custom-file-input">
这样即使元素被重置,只要class保留,样式就不会丢失,仅需恢复size和title属性即可。
内容的提问来源于stack exchange,提问作者noobienerd
相关产品推荐
相关产品推荐

