По умолчанию браузеры визуализирует HTML <input type="file">
по-разному, даже если вы попытаетесь стилизовать его с помощью CSS-свойств, у вас это не получится. Но вы можете использовать CSS-свойство opacity
и position
в сочетании с jQuery-методом change()
для создания собственного, кроссбраузерного элемента управления HTML-формой для загрузки файлов.
Давайте посмотрим на следующий пример, чтобы понять, как это работает:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom File Input Field with CSS and jQuery</title>
<style>
.custom-file-input{
display: inline-block;
overflow: hidden;
position: relative;
}
.custom-file-input input[type="file"]{
width: 100%;
height: 100%;
opacity: 0;
filter: alpha(opacity=0);
zoom: 1; /* Fix for IE7 */
position: absolute;
top: 0;
left: 0;
z-index: 999;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$('.custom-file-input input[type="file"]').change(function(e){
$(this).siblings('input[type="text"]').val(e.target.files[0].name);
});
});
</script>
</head>
<body>
<form>
<div class="custom-file-input">
<input type="file">
<input type="text">
<input type="button" value="Attach">
</div>
</form>
</body>
</html>