我是新来的JavaScript和我无法改变我的自定义文件上传按钮的标签文件已被选定后,显示的文件名。
试图按照these steps。
按钮正确显示和文件上传,但我不能设法让JS工作,以显示在按钮上的上传的文件名。
var inputs = document.querySelectorAll('.wpcf7-file');
Array.prototype.forEach.call(inputs, function(input) {
input.addEventListener('change', function(e) {
var label = document.querySelectorAll('.custom-file-button');
var fileName = '';
fileName = e.target.value.split('\\').pop();
if (fileName) {
label.innerHTML = fileName;
} else
label.innerHTML = labelVal;
});
});
label.custom-file-button {
position: relative;
}
label.custom-file-button:before {
content: "📷 Take or upload picture";
position: absolute;
left: 0;
padding: 10px;
background: #1b87d5;
color: #fff;
width: auto;
text-align: center;
border-radius: 5px;
cursor: pointer;
}
label.custom-file-button:hover:before {
background: #146bac;
}
.custom-file-input {
visibility: hidden;
}
<div class="limit-to-view">
<label class="wpcf7-form-control-wrap custom-file-button">
<span class="wpcf7-form-control-wrap custom-file-input">
<input type="file" name="custom-file-input" size="40" class="wpcf7-form-control wpcf7-file" accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.ppt,.pptx,.odt,.avi,.ogg,.m4a,.mov,.mp3,.mp4,.mpg,.wav,.wmv" aria-invalid="false">
</span>
</label>
</div>
.querySelectorAll()
返回一个NodeList
,而不是一个单一的元件。替补.closest()
为.querySelectorAll()
选择最近的祖先<label>
元素当前<input type="file">
元素。由于<input type="file">
元素是<label>
.innerHTML
设置为文件名会覆盖<input type="file">
元素的孩子。在CSS不显示<span>
元素是<label>
的第一个孩子,增加了<span>
显示文件名.nextElementSibling
元素的<label>
。您可以使用e.target.files[0].name
来获取文件名。
var inputs = document.querySelectorAll('.wpcf7-file');
Array.prototype.forEach.call(inputs, function(input) {
input.addEventListener('change', function(e) {
var label = e.target.closest('.custom-file-button');
label.nextElementSibling.innerHTML = e.target.files[0].name;
});
});
label.custom-file-button {
position: relative;
}
label.custom-file-button:before {
content: "📷 Take or upload picture";
position: absolute;
left: 0;
padding: 10px;
background: #1b87d5;
color: #fff;
width: auto;
text-align: center;
border-radius: 5px;
cursor: pointer;
}
label.custom-file-button:hover:before {
background: #146bac;
}
.custom-file-input {
visibility: hidden;
}
<div class="limit-to-view">
<label class="wpcf7-form-control-wrap custom-file-button">
<span class="wpcf7-form-control-wrap custom-file-input">
<input type="file" name="custom-file-input" size="40" class="wpcf7-form-control wpcf7-file" accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.ppt,.pptx,.odt,.avi,.ogg,.m4a,.mov,.mp3,.mp4,.mpg,.wav,.wmv" aria-invalid="false">
</span>
</label>
<span></span>
</div>