它已經有一段時間,因爲我問了這個問題,下面是我現在用於樣式文件輸入的方法。此信息來自Codrops。它會進入更多的細節,並提供了幾個例子,但這裏有最基礎的:
HTML
<input type="file" name="file" id="file" class="inputfile" />
<label for="file">Choose a file</label>
需要檢查JS
<html class="no-js">
<head>
<!-- remove this if you use Modernizr -->
<script>(function(e,t,n){var r=e.querySelectorAll("html")[0];r.className=r.className.replace(/(^|\s)no-js(\s|$)/,"$1js$2")})(document,window,0);</script>
</head>
</html>
CSS
.js .inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.inputfile + label {
max-width: 80%;
font-size: 1.25rem;
/* 20px */
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
display: inline-block;
overflow: hidden;
padding: 0.625rem 1.25rem;
/* 10px 20px */
}
.no-js .inputfile + label {
display: none;
}
.inputfile:focus + label,
.inputfile.has-focus + label {
outline: 1px dotted #000;
outline: -webkit-focus-ring-color auto 5px;
}
.inputfile + label * {
/* pointer-events: none; */
/* in case of FastClick lib use */
}
.inputfile + label svg {
width: 1em;
height: 1em;
vertical-align: middle;
fill: currentColor;
margin-top: -0.25em;
/* 4px */
margin-right: 0.25em;
/* 4px */
}
JS
;(function (document, window, index)
{
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;
});
// Firefox bug fix
input.addEventListener('focus', function(){ input.classList.add('has-focus'); });
input.addEventListener('blur', function(){ input.classList.remove('has-focus'); });
});
}(document, window, 0));
來源
2016-05-02 19:53:10
L84
樣式化的輸入類型=「文件」 ... FML :) – tybro0103