Java 脚本函数无法正常替换标签上所选文件的名称
Java Script function not working correctly to replace the name of the selected file on the label tag
我正在尝试使用代码通过 CSS 和 JS 更改 html 中 file
类型按钮的样式。不知何故,JS 功能无法正常工作,并且没有替换标签上所选文件的名称。以下是 jsfiddle 中的代码:See the codes in jsfiddle
感谢任何帮助!
html:
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file"><strong>Choose a file</strong></label>
css:
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
}
.inputfile:focus + label,
.inputfile + label:hover {
background-color: red;
}
.inputfile + label {
cursor: pointer; /* "hand" cursor */
}
js:
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
您的标签中没有 span 标签
改变这个
label.querySelector( 'span' ).innerHTML = fileName;
对此
label.querySelector( 'strong' ).innerHTML = fileName;
我正在尝试使用代码通过 CSS 和 JS 更改 html 中 file
类型按钮的样式。不知何故,JS 功能无法正常工作,并且没有替换标签上所选文件的名称。以下是 jsfiddle 中的代码:See the codes in jsfiddle
感谢任何帮助!
html:
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file"><strong>Choose a file</strong></label>
css:
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
}
.inputfile:focus + label,
.inputfile + label:hover {
background-color: red;
}
.inputfile + label {
cursor: pointer; /* "hand" cursor */
}
js:
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
您的标签中没有 span 标签
改变这个
label.querySelector( 'span' ).innerHTML = fileName;
对此
label.querySelector( 'strong' ).innerHTML = fileName;