Programing

파일 업로드 버튼에 대한 브라우저 간 사용자 지정 스타일 지정

lottogame 2020. 8. 15. 09:47
반응형

파일 업로드 버튼에 대한 브라우저 간 사용자 지정 스타일 지정


이 질문에 이미 답변이 있습니다.

개인 취향에 맞게 파일 업로드 버튼을 스타일링하려고하는데 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!!에서 두 번째 데모 버튼 아래를클릭하면어쨌든 파일 대화 상자가 열리지 만 다른 모든 브라우저에서도 파일 버튼이 버튼의 올바른 영역을 차지하지 않습니다.

자바 스크립트없이 파일 업로드 버튼의 스타일을 지정하는 더 확실한 방법이 있습니까? 가능하면 '해키'코딩을 가능한 한 적게 사용하는 것이 좋습니까? (해킹은 일반적으로 바이올린과 같은 다른 문제를 동반하기 때문입니다)?


놀랍게도 내가 이것을 추천 한 다른 장소가 없었기 때문에 이것을 게시하고 있습니다.

브라우저 정의 입력 차원으로 제한하지 않고이 작업을 수행하는 정말 쉬운 방법이 있습니다. <label>숨겨진 파일 업로드 버튼 주위에 태그를 사용하십시오 . 이것은 웹킷의 내장 스타일을 통해 허용 된 스타일보다 훨씬 더 자유로운 스타일링을 가능하게 합니다 [1] .

라벨 태그는 클릭 이벤트를 하위 입력 [2] 으로 보내는 정확한 목적으로 만들어 졌으므로이를 사용하면 더 이상 클릭 이벤트를 입력 버튼으로 보내는 데 자바 스크립트가 필요하지 않습니다. 다음과 같은 것을 사용합니다.

label.myLabel input[type="file"] {
    position:absolute;
    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>

나는 고정 된 위치를 사용하여 입력을 숨기고, 이전 버전의 Internet Explorer에서도 작동하도록했습니다 (에뮬레이트 된 IE8- visibility:hidden또는 display:none파일 입력 에서 작동하지 않음 ). 에뮬레이트 된 IE7 이상에서 테스트했으며 완벽하게 작동했습니다.


  1. 안타깝게도 태그 <button>안에 s를 사용할 수 없으므로 <label>버튼의 스타일을 직접 정의해야합니다. 나에게는 이것이이 접근 방식의 유일한 단점입니다.
  2. 경우] for속성이 정의되고, 그 값과 동일한 입력 트리거 사용 id은 AS for상의 특성 <label>.

모든 브라우저에서 작동하는 방법을 아래에서 찾으십시오. 기본적으로 이미지 위에 입력을 넣습니다. 사용자가 항상 업로드 버튼을 클릭하도록 글꼴 크기를 사용하여 크게 만듭니다.

.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>


가장 좋은 예는 이것, No hide, 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">


이것은 사업을 꽤 잘 처리하는 것 같습니다. 여기에 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;
}

모든 파일 입력을 다루는 쉬운 방법은 입력 [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();
    });
});

다음은 http://cssdeck.com/labs/beautiful-flat-buttons 에서 가져온 샘플 버튼 CSS입니다 .

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;
}

I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.

the directive

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
        })

      }

    };
  });

a jade template if you are using jade

div(class="file-upload-container") 
    button(class="file-upload-button") +
    input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")  

the same template in html if you are using 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>

the 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;
}

It's also easy to style the label if you are working with Bootstrap and LESS:

label {
    .btn();
    .btn-primary();

    > input[type="file"] {
        display: none;
    }
}

참고URL : https://stackoverflow.com/questions/21842274/cross-browser-custom-styling-for-file-upload-button

반응형