Межстраничный пользовательский стиль для кнопки загрузки файлов
Я пытаюсь настроить кнопку загрузки файлов на свои личные предпочтения, но я не мог найти действительно надежных способов сделать это без JS. Я нашел два другие вопросы по этому вопросу, но ответы там либо включали JavaScript, либо предлагали Подход Quirksmode.
Моя основная проблема с этим подходом Quirksmode заключается в том, что кнопка файла по-прежнему будет иметь размеры, определенные браузером, поэтому она не будет автоматически настраиваться на все, что используется как кнопка, расположенная под ней. Я создал код на основе этого, но он просто займет пространство, в которое обычно будет зависеть файл, поэтому он вообще не будет заполнять родительский div, как я этого хочу.
HTML:
<div class="myLabel">
<input type="file"/>
<span>My Label</span>
</div>
CSS
.myLabel {
position: relative;
}
.myLabel input {
position: absolute;
z-index: 2;
opacity: 0;
width: 100%;
height: 100%;
}
Эта сценария демонстрирует, как этот подход является довольно ошибочным. В Chrome, нажав кнопку !!
ниже второй демонстрационной кнопки, все равно откроется диалоговое окно файла, но также и во всех других браузерах кнопка с файлом не займет правильные области кнопки.
Есть ли более надежный способ стилизации кнопки загрузки файла без какого-либо JavaScript, и желательно использовать как можно меньше "хакерского" кодирования (так как хакинг обычно приносит другие проблемы вместе с ним, например, те, что в скрипке)
Ответы
Ответ 1
Я публикую это, потому что (к моему удивлению) не было другого места, которое я мог бы найти, который рекомендовал это.
Там действительно простой способ сделать это, не ограничивая вас определенными браузером размерами ввода. Просто используйте тег <label>
вокруг скрытой кнопки загрузки файлов. Это позволяет еще больше свободы стилизации, чем стиль, разрешенный с помощью встроенного стиля webkit [1].
Тег ярлыка был сделан для конкретной цели - направлять любые события клика на него дочерним входам [2] поэтому, используя это, вам не понадобится JavaScript, чтобы направить событие click для кнопки ввода для вас. Вы должны использовать что-то вроде следующего:
label.myLabel input[type="file"] {
position: fixed;
top: -1000px;
}
/***** Example custom styling *****/
.myLabel {
border: 2px solid #AAA;
border-radius: 4px;
padding: 2px 5px;
margin: 2px;
background: #DDD;
display: inline-block;
}
.myLabel:hover {
background: #CCC;
}
.myLabel:active {
background: #CCF;
}
.myLabel :invalid + span {
color: #A44;
}
.myLabel :valid + span {
color: #4A4;
}
<label class="myLabel">
<input type="file" required/>
<span>My Label</span>
</label>
Ответ 2
Ниже вы найдете способ, который работает во всех браузерах. В основном я помещаю ввод поверх изображения.
Я делаю это огромным, используя размер шрифта, поэтому пользователь всегда нажимает кнопку загрузки.
.myFile {
position: relative;
overflow: hidden;
float: left;
clear: left;
}
.myFile input[type="file"] {
display: block;
position: absolute;
top: 0;
right: 0;
opacity: 0;
font-size: 100px;
filter: alpha(opacity=0);
cursor: pointer;
}
<label class="myFile">
<img src="http://wscont1.apps.microsoft.com/winstore/1x/c37a9d99-6698-4339-acf3-c01daa75fb65/Icon.13385.png" alt="" />
<input type="file" />
</label>
Ответ 3
Лучшим примером является тот, который не скрывает, No jQuery, полностью чистый CSS
http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/
.custom-file-input::-webkit-file-upload-button {
visibility: hidden;
}
.custom-file-input::before {
content: 'Select some files';
display: inline-block;
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);
border: 1px solid #999;
border-radius: 3px;
padding: 5px 8px;
outline: none;
white-space: nowrap;
-webkit-user-select: none;
cursor: pointer;
text-shadow: 1px 1px #fff;
font-weight: 700;
font-size: 10pt;
}
.custom-file-input:hover::before {
border-color: black;
}
.custom-file-input:active::before {
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);
}
<input type="file" class="custom-file-input">
Ответ 4
Это, по-видимому, хорошо заботится о бизнесе. Здесь находится fidde:
HTML
<label for="upload-file">A proper input label</label>
<div class="upload-button">
<div class="upload-cover">
Upload text or whatevers
</div>
<!-- this is later in the source so it'll be "on top" -->
<input name="upload-file" type="file" />
</div> <!-- .upload-button -->
CSS
/* first things first - get your box-model straight*/
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
label {
/* just positioning */
float: left;
margin-bottom: .5em;
}
.upload-button {
/* key */
position: relative;
overflow: hidden;
/* just positioning */
float: left;
clear: left;
}
.upload-cover {
/* basically just style this however you want - the overlaying file upload should spread out and fill whatever you turn this into */
background-color: gray;
text-align: center;
padding: .5em 1em;
border-radius: 2em;
border: 5px solid rgba(0,0,0,.1);
cursor: pointer;
}
.upload-button input[type="file"] {
display: block;
position: absolute;
top: 0; left: 0;
margin-left: -75px; /* gets that button with no-pointer-cursor off to the left and out of the way */
width: 200%; /* over compensates for the above - I would use calc or sass math if not here*/
height: 100%;
opacity: .2; /* left this here so you could see. Make it 0 */
cursor: pointer;
border: 1px solid red;
}
.upload-button:hover .upload-cover {
background-color: #f06;
}
Ответ 5
Любой простой способ охватить ВСЕ входные файлы - это просто стиль ввода [type = button] и сбросить его во всем мире, чтобы вставить файлы в кнопки:
$(document).ready(function() {
$("input[type=file]").each(function () {
var thisInput$ = $(this);
var newElement = $("<input type='button' value='Choose File' />");
newElement.click(function() {
thisInput$.click();
});
thisInput$.after(newElement);
thisInput$.hide();
});
});
Вот несколько примеров кнопок CSS, которые я получил от http://cssdeck.com/labs/beautiful-flat-buttons:
input[type=button] {
position: relative;
vertical-align: top;
width: 100%;
height: 60px;
padding: 0;
font-size: 22px;
color:white;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
background: #454545;
border: 0;
border-bottom: 2px solid #2f2e2e;
cursor: pointer;
-webkit-box-shadow: inset 0 -2px #2f2e2e;
box-shadow: inset 0 -2px #2f2e2e;
}
input[type=button]:active {
top: 1px;
outline: none;
-webkit-box-shadow: none;
box-shadow: none;
}
Ответ 6
Я только что наткнулся на эту проблему и написал решение для тех из вас, кто использует Angular. Вы можете написать настраиваемую директиву, состоящую из контейнера, кнопки и элемента ввода с файлом типа. С помощью CSS вы помещаете ввод через настраиваемую кнопку, но с непрозрачностью 0. Вы устанавливаете высоту и ширину контейнеров в точности ширину и высоту смещения кнопки, а также высоту и ширину ввода до 100% контейнера.
директива
angular.module('myCoolApp')
.directive('fileButton', function () {
return {
templateUrl: 'components/directives/fileButton/fileButton.html',
restrict: 'E',
link: function (scope, element, attributes) {
var container = angular.element('.file-upload-container');
var button = angular.element('.file-upload-button');
container.css({
position: 'relative',
overflow: 'hidden',
width: button.offsetWidth,
height: button.offsetHeight
})
}
};
});
шаблон нефрита, если вы используете нефрит
div(class="file-upload-container")
button(class="file-upload-button") +
input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")
тот же шаблон в html, если вы используете html
<div class="file-upload-container">
<button class="file-upload-button"></button>
<input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" />
</div>
css
.file-upload-button {
margin-top: 40px;
padding: 30px;
border: 1px solid black;
height: 100px;
width: 100px;
background: transparent;
font-size: 66px;
padding-top: 0px;
border-radius: 5px;
border: 2px solid rgb(255, 228, 0);
color: rgb(255, 228, 0);
}
.file-upload-input {
position: absolute;
top: 0;
left: 0;
z-index: 2;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
Ответ 7
Также легко стилизовать метку, если вы работаете с Bootstrap и LESS:
label {
.btn();
.btn-primary();
> input[type="file"] {
display: none;
}
}