Programing

입력 유형 지정 = "파일"버튼

lottogame 2020. 10. 2. 21:24
반응형

입력 유형 지정 = "파일"버튼


입력 type="file"버튼의 스타일을 어떻게 지정합니까 ?


대부분의 브라우저는 CSS 또는 자바 스크립트에서 모양을 변경하지 않기 때문에 파일 입력 스타일 지정은 매우 어렵습니다.

입력 크기조차도 다음과 같은 항목에 응답하지 않습니다.

<input type="file" style="width:200px">

대신 size 속성을 사용해야합니다.

<input type="file" size="60" />

그보다 더 정교한 스타일링 (예 : 찾아보기 버튼 모양 변경)의 경우 기본 파일 입력 위에 스타일이 지정된 버튼과 입력 상자를 오버레이하는 까다로운 접근 방식을 살펴 봐야합니다. rm이 www.quirksmode.org/dom/inputfile.html 에서 이미 언급 한 기사 는 제가 본 것 중 최고입니다.


이를 위해 JavaScript가 필요하지 않습니다! 다음은 브라우저 간 솔루션입니다.

이 예를보십시오! -Chrome / FF / IE에서 작동-(IE10 / 9 / 8 / 7)

가장 좋은 방법은 숨겨진 파일 입력 요소에 for속성이 첨부 된 사용자 정의 레이블 요소를 갖는 입니다. (이 작업을 수행 하려면 레이블의 속성이 파일 요소 속성과 일치해야합니다 .)forid

<label for="file-upload" class="custom-file-upload">
    Custom Upload
</label>
<input id="file-upload" type="file"/>

또는 파일 입력 요소를 레이블로 직접 래핑 할 수도 있습니다. (예제)

<label class="custom-file-upload">
    <input type="file"/>
    Custom Upload
</label>

스타일링 측면 에서 속성 선택기를 사용하여 입력 요소 1을 숨 깁니다 .

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

그런 다음 사용자 지정 label요소의 스타일을 지정하기 만하면됩니다. (예) .

.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

1-를 사용하여 요소를 숨기면 display: noneIE8 이하에서는 작동하지 않는다는 점에 주목할 가치가 있습니다. 또한 jQuery validate 기본적으로 숨겨진 필드의 유효성을 검사 하지 않는다는 사실을 알고 있어야합니다 . 두 가지 중 하나가 문제가되는 경우 이러한 상황에서 작동 하는 입력 ( 1 , 2 ) 을 숨기는 두 가지 다른 방법 이 있습니다.


다음 단계에 따라 파일 업로드 양식에 대한 사용자 지정 스타일을 만들 수 있습니다.

  1. 이것은 간단한 HTML 형식입니다 (아래에 제가 작성한 HTML 주석을 읽으십시오)

    <form action="#type your action here" method="POST" enctype="multipart/form-data">
      <div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
      <!-- this is your file input tag, so i hide it!-->
      <div style='height: 0px;width:0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
      <!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
      <input type="submit" value='submit' >
    </form>
    
  2. 그런 다음이 간단한 스크립트를 사용하여 클릭 이벤트를 파일 입력 태그에 전달합니다.

    function getFile(){
         document.getElementById("upfile").click();
    }
    

    이제 기본 스타일을 변경하는 방법에 대해 걱정하지 않고 모든 유형의 스타일을 사용할 수 있습니다.

한 달 반 동안 기본 스타일을 변경하려고했기 때문에 이것을 잘 알고 있습니다. 저를 믿으십시오. 브라우저마다 업로드 입력 태그가 다르기 때문에 매우 어렵습니다. 따라서 이것을 사용하여 사용자 정의 파일 업로드 양식을 작성하십시오. 다음은 전체 자동 업로드 코드입니다.

function getFile() {
  document.getElementById("upfile").click();
}

function sub(obj) {
  var file = obj.value;
  var fileName = file.split("\\");
  document.getElementById("yourBtn").innerHTML = fileName[fileName.length - 1];
  document.myForm.submit();
  event.preventDefault();
}
#yourBtn {
  position: relative;
  top: 150px;
  font-family: calibri;
  width: 150px;
  padding: 10px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border: 1px dashed #BBB;
  text-align: center;
  background-color: #DDD;
  cursor: pointer;
}
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
  <div id="yourBtn" onclick="getFile()">click to upload a file</div>
  <!-- this is your file input tag, so i hide it!-->
  <!-- i used the onchange event to fire the form submission-->
  <div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)" /></div>
  <!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
  <!-- <input type="submit" value='submit' > -->
</form>


CSS로 숨기고 $ (selector) .click ()과 함께 사용자 정의 버튼을 사용하여 찾아보기 버튼을 활성화하십시오. 그런 다음 파일 입력 유형의 값을 확인하는 간격을 설정하십시오. 간격은 사용자에 대한 값을 표시하여 사용자가 업로드되는 내용을 볼 수 있습니다. 양식이 제출되면 간격이 지워집니다. [편집] 죄송합니다.이 게시물을 업데이트하려는 의도로 바빴습니다. 여기에 예가 있습니다.

<form action="uploadScript.php" method="post" enctype="multipart/form-data">
<div>
    <!-- filename to display to the user -->
    <p id="file-name" class="margin-10 bold-10"></p>

    <!-- Hide this from the users view with css display:none; -->
    <input class="display-none" id="file-type" type="file" size="4" name="file"/>

    <!-- Style this button with type image or css whatever you wish -->
    <input id="browse-click" type="button" class="button" value="Browse for files"/>

    <!-- submit button -->
    <input type="submit" class="button" value="Change"/>
</div>

$(window).load(function () {
    var intervalFunc = function () {
        $('#file-name').html($('#file-type').val());
    };
    $('#browse-click').on('click', function () { // use .live() for older versions of jQuery
        $('#file-type').click();
        setInterval(intervalFunc, 1);
        return false;
    });
});

HTML

<div class="new_Btn">SelectPicture</div><br>
<input id="html_btn" type='file'" /><br>

CSS

.new_Btn {
// your css propterties
}

#html_btn {
 display:none;
}

jQuery

$('.new_Btn').bind("click" , function () {
        $('#html_btn').click();
    });
//edit: 6/20/2014: Be sure to use ".on" not ".bind" for newer versions of jQuery

바이올린 : http://jsfiddle.net/M7BXC/

일반 JavaScript로 jQuery 없이도 목표를 달성 할 수 있습니다.

이제 newBtn은 html_btn과 연결되며 원하는대로 새 btn을 스타일링 할 수 있습니다.


모든 렌더링 엔진은 <input type="file">이 생성 될 때 자동으로 버튼을 생성합니다. 역사적으로이 버튼은 완전히 스타일링이 불가능했습니다. 그러나 Trident와 WebKit은 의사 요소를 통해 후크를 추가했습니다.

삼지창

IE10부터는 ::-ms-browse의사 요소를 사용하여 파일 입력 버튼의 스타일을 지정할 수 있습니다 . 기본적으로 일반 버튼에 적용하는 CSS 규칙은 의사 요소에 적용 할 수 있습니다. 예를 들면 :

::-ms-browse {
  background: black;
  color: red;
  padding: 1em;
}
<input type="file">

이것은 Windows 8의 IE10에서 다음과 같이 표시됩니다.

이것은 Windows 8의 IE10에서 다음과 같이 표시됩니다.

WebKit

WebKit은 ::-webkit-file-upload-button의사 요소 가있는 파일 입력 버튼에 대한 후크를 제공합니다 . 다시 말하지만, 거의 모든 CSS 규칙을 적용 할 수 있으므로 Trident 예제도 여기에서 작동합니다.

::-webkit-file-upload-button {
  background: black;
  color: red;
  padding: 1em;
}
<input type="file">

OS X의 Chrome 26에서 다음과 같이 표시됩니다.

OS X의 Chrome 26에서 다음과 같이 표시됩니다.


Bootstrap 3을 사용하는 경우 이것은 나를 위해 일했습니다.

참조 http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/를

.btn-file {
  position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  font-size: 100px;
  text-align: right;
  filter: alpha(opacity=0);
  opacity: 0;
  outline: none;
  background: white;
  cursor: inherit;
  display: block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<span class="btn btn-primary btn-file">
    Browse...<input type="file">
</span>

다음 파일 입력 버튼을 생성합니다.

예제 버튼

진지하게, http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/을 확인 하십시오.


아래 코드를 사용하여 순수한 CSS로 할 수 있습니다. 저는 부트 스트랩과 글꼴을 사용했습니다.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />

<label class="btn btn-default btn-sm center-block btn-file">
  <i class="fa fa-upload fa-2x" aria-hidden="true"></i>
  <input type="file" style="display: none;">
</label>


 <label>
    <input type="file" />
 </label>

입력에 대한 레이블 안에 입력 type = "file"을 래핑 할 수 있습니다. 원하는대로 레이블 스타일을 지정하고 display : none;


네이티브 드래그 앤 드롭 지원이있는 작업 예제 : https://jsfiddle.net/j40xvkb3/

파일 입력의 스타일을 지정할 때 입력이 제공하는 기본 상호 작용을 중단해서는 안됩니다 .

display: none접근 방식은 기본 드래그 앤 드롭 지원을 중단합니다.

아무것도 깨뜨리지 않으려면 opacity: 0입력에 대한 접근 방식을 사용하고 래퍼의 상대 / 절대 패턴을 사용하여 배치해야합니다.

이 기술을 사용하면 사용자를위한 클릭 / 드롭 영역의 스타일을 쉽게 지정할 수 있으며 dragenter이벤트시 자바 스크립트에 사용자 정의 클래스를 추가 하여 스타일을 업데이트하고 사용자가 파일을 드롭 할 수 있음을 알 수 있도록 피드백을 제공 할 수 있습니다.

HTML :

<label for="test">
  <div>Click or drop something here</div>
  <input type="file" id="test">
</label>

CSS :

input[type="file"] {
  position: absolute;
  left: 0;
  opacity: 0;
  top: 0;
  bottom: 0;
  width: 100%;
}

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ccc;
  border: 3px dotted #bebebe;
  border-radius: 10px;
}

label {
  display: inline-block;
  position: relative;
  height: 100px;
  width: 400px;
}

다음은 작업 예제입니다 ( dragover이벤트 및 삭제 된 파일 을 처리하기위한 추가 JS 포함 ).

https://jsfiddle.net/j40xvkb3/

이것이 도움이 되었기를 바랍니다!


이것은 jquery로 간단합니다. 약간 수정하여 Ryan 의 제안에 대한 코드 예제를 제공합니다 .

기본 HTML :

<div id="image_icon"></div>
<div id="filename"></div>
<input id="the_real_file_input" name="foobar" type="file">

준비가되면 입력에 스타일을 opacity: 0설정 display: none해야합니다. 클릭 할 수 있어야하므로 설정할 수 없습니다 . 그러나 원하는 경우 "새로 만들기"버튼 아래에 배치하거나 Z- 색인을 사용하여 다른 항목 아래에 넣을 수 있습니다.

이미지를 클릭 할 때 실제 입력을 클릭하도록 jquery를 설정하십시오.

$('#image_icon').click(function() {
    $('#the_real_file_input').click();
});

이제 버튼이 작동합니다. 값이 변경되면 잘라서 붙여 넣기 만하면됩니다.

$('input[type=file]').bind('change', function() {
    var str = "";
    str = $(this).val();
    $("#filename").text(str);
}).change();

Tah dah! val ()을 더 의미있는 것으로 구문 분석해야 할 수도 있지만 모두 설정해야합니다.


다음은 실제로 <input type="file" />요소의 스타일을 지정하지 않고 대신 <input type="file" />다른 요소 (스타일링 가능) 위에 요소를 사용 하는 솔루션입니다 . <input type="file" />요소는 따라서 정말 보이지 않는, 전체 환상은 멋지게 스타일 파일 업로드 컨트롤이다.

나는 최근 에이 문제를 발견했으며 Stack Overflow에 대한 과다한 답변에도 불구하고 실제로 법안에 맞는 것은 없었습니다. 결국 간단하고 우아한 솔루션을 갖기 위해 이것을 커스터마이징했습니다.

Firefox, IE (11, 10 및 9), Chrome 및 Opera, iPad 및 몇 가지 Android 기기에서도 테스트했습니다.

다음은 JSFiddle 링크입니다-> http://jsfiddle.net/umhva747/

$('input[type=file]').change(function(e) {
    $in = $(this);
    $in.next().html($in.val());
    
});

$('.uploadButton').click(function() {
    var fileName = $("#fileUpload").val();
    if (fileName) {
        alert(fileName + " can be uploaded.");
    }
    else {
        alert("Please select a file to upload");
    }
});
body {
    background-color:Black;
}

div.upload {
    background-color:#fff;
    border: 1px solid #ddd;
    border-radius:5px;
    display:inline-block;
    height: 30px;
    padding:3px 40px 3px 3px;
    position:relative;
    width: auto;
}

div.upload:hover {
    opacity:0.95;
}

div.upload input[type="file"] {
    display: input-block;
    width: 100%;
    height: 30px;
    opacity: 0;
    cursor:pointer;
    position:absolute;
    left:0;
}
.uploadButton {
    background-color: #425F9C;
    border: none;
    border-radius: 3px;
    color: #FFF;
    cursor:pointer;
    display: inline-block;
    height: 30px;
    margin-right:15px;
    width: auto;
    padding:0 20px;
    box-sizing: content-box;
}

.fileName {
    font-family: Arial;
    font-size:14px;
}

.upload + .uploadButton {
    height:38px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data">
    <div class="upload">
        <input type="button" class="uploadButton" value="Browse" />
        <input type="file" name="upload" accept="image/*" id="fileUpload" />
        <span class="fileName">Select file..</span>
    </div>
    <input type="button" class="uploadButton" value="Upload File" />
</form>

도움이 되었기를 바랍니다!!!


가시성 : 숨겨진 트릭

나는 보통 visibility:hidden속임수에 간다

이것은 내 스타일의 버튼입니다

<div id="uploadbutton" class="btn btn-success btn-block">Upload</div>

이것은 입력 유형 = 파일 버튼입니다. visibility:hidden규칙에 유의하십시오.

<input type="file" id="upload" style="visibility:hidden;">

이것은 그것들을 함께 붙이는 자바 스크립트 비트입니다. 효과가있다

<script>
 $('#uploadbutton').click(function(){
    $('input[type=file]').click();
 });
 </script>

내가 생각할 수있는 유일한 방법은 렌더링 된 후 자바 스크립트로 버튼을 찾고 스타일을 할당하는 것입니다.

이 글을 볼 수도 있습니다.


<input type="file" name="media" style="display-none" onchange="document.media.submit()">

나는 일반적으로 간단한 자바 스크립트를 사용하여 파일 입력 태그를 사용자 정의합니다. 숨겨진 입력 필드, 버튼 클릭시 자바 스크립트는 숨겨진 필드, CSS 또는 jquery 무리가없는 간단한 솔루션을 호출합니다.

<button id="file" onclick="$('#file').click()">Upload File</button>

멋진 버튼이나 요소 위에 파일 업로드 버튼을 놓고 숨 깁니다.

매우 간단하며 모든 브라우저에서 작동합니다.

<div class="upload-wrap">
    <button type="button" class="nice-button">upload_file</button>
    <input type="file" name="file" class="upload-btn">
</div>

스타일

.upload-wrap {
    position: relative;
}

.upload-btn {
    position: absolute;
    left: 0;
    opacity: 0;
}

여기서는 span을 사용하여 파일 유형의 입력을 트리거하고 단순히 해당 span을 사용자 정의 하여 이러한 방식으로 모든 스타일을 추가 할 수 있습니다.

참고 숨겨진 옵션과 범위에 트리거 : 우리는 가시성 입력 태그를 사용하는 것이.

.attachFileSpan{
color:#2b6dad;
cursor:pointer;
}
.attachFileSpan:hover{
text-decoration: underline;
}
<h3> Customized input of type file </h3>
<input id="myInput" type="file" style="visibility:hidden"/>

        <span title="attach file" class="attachFileSpan" onclick="document.getElementById('myInput').click()">
        Attach file
        </span>

참고


CSS 만

이 매우 간단 하고 쉬운 사용

HTML :

<label>Attach your screenshort</label>
                <input type="file" multiple class="choose">

CSS :

.choose::-webkit-file-upload-button {
    color: white;
    display: inline-block;
    background: #1CB6E0;
    border: none;
    padding: 7px 15px;
    font-weight: 700;
    border-radius: 3px;
    white-space: nowrap;
    cursor: pointer;
    font-size: 10pt;
}

아마 많은 awnsers. 그러나 나는 fa- 버튼이있는 순수한 CSS에서 이것을 좋아합니다.

.divs {
    position: relative;
    display: inline-block;
    background-color: #fcc;
}

.inputs {
    position:absolute;
    left: 0px;
    height: 100%;
    width: 100%;
    opacity: 0;
    background: #00f;
    z-index:999;
}

.icons {
    position:relative;
}
<div class="divs">
<input type='file' id='image' class="inputs">
<i class="fa fa-image fa-2x icons"></i>
</div>

<div class="divs">
<input type='file' id='book' class="inputs">
<i class="fa fa-book fa-5x icons"></i>
</div>
<br><br><br>
<div class="divs">
<input type='file' id='data' class="inputs">
<i class="fa fa-id-card fa-3x icons"></i>
</div>





<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

바이올린 : https://jsfiddle.net/zoutepopcorn/v2zkbpay/1/


이것은 자료 / 각도 파일 업로드로 할 수있는 좋은 방법입니다. 부트 스트랩 버튼으로도 똑같이 할 수 있습니다.

내가 사용하는 참고 <a>대신 <button>이 거품이 최대 클릭 이벤트를 할 수 있습니다.

<label>
    <input type="file" (change)="setFile($event)" style="display:none" />

    <a mat-raised-button color="primary">
      <mat-icon>file_upload</mat-icon>
      Upload Document
    </a>

  </label>

다음은 선택한 파일 이름을 보여주는 솔루션입니다. http://jsfiddle.net/raft9pg0/1/

HTML :

<label for="file-upload" class="custom-file-upload">Chose file</label>
<input id="file-upload" type="file"/>
File: <span id="file-upload-value">-</span>

JS :

$(function() {
    $("input:file[id=file-upload]").change(function() {
        $("#file-upload-value").html( $(this).val() );
    });
});

CSS :

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

.custom-file-upload {
      background: #ddd;
      border: 1px solid #aaa;
      border-top: 1px solid #ccc;
      border-left: 1px solid #ccc;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      border-radius: 3px;
      color: #444;
      display: inline-block;
      font-size: 11px;
      font-weight: bold;
      text-decoration: none;
      text-shadow: 0 1px rgba(255, 255, 255, .75);
      cursor: pointer;
      margin-bottom: 20px;
      line-height: normal;
      padding: 8px 10px; }

이번 주에는 버튼을 사용자 지정하고 선택한 파일 이름을 옆에 표시해야했기 때문에 위의 답변 중 일부를 읽은 후 (Thanks BTW) 다음 구현을 생각해 냈습니다.

HTML :

<div class="browse">
<label id="uploadBtn" class="custom-file-upload">Choose file
<input type="file" name="fileInput" id="fileInput" accept=".yaml" ngf-select ngf-change="onFileSelect($files)" />
</label>
<span>{{fileName}}</span>
</div>

CSS

   input[type='file'] {
    color: #a1bbd5;
    display: none;

}

.custom-file-upload {
    border: 1px solid #a1bbd5;
    display: inline-block;
    padding: 2px 8px;
    cursor: pointer;
}

label{
    color: #a1bbd5;
    border-radius: 3px;
}

자바 스크립트 (Angular)

app.controller('MainCtrl', function($scope) {

        $scope.fileName = 'No file chosen';

          $scope.onFileSelect = function ($files) {
          $scope.selectedFile = $files;
          $scope.fileName = $files[0].name;
    };
});

기본적으로 저는 ng-file-upload lib로 작업하고 있습니다. Angular-wise는 파일 이름을 $ scope에 바인딩하고 '선택된 파일 없음'의 초기 값을 지정하고 있으며 onFileSelect () 함수를 다음에 바인딩합니다. 내 범위 그래서 파일이 선택되면 ng-upload API를 사용하여 파일 이름을 얻고 $ scope.filename에 할당합니다.


실제로 매우 브라우저에 특화된 "훌륭한"CSS 전용 솔루션이나 실제 버튼 위에 스타일이 지정된 버튼을 오버레이하거나 , 또는 다른 해킹 <label>대신 을 사용하도록 강요하는 "훌륭한"CSS 전용 솔루션에 속지 마십시오. <button>. 일반적인 용도로 작동하려면 JavaScript가 필요합니다. 나를 믿지 않는다면 gmail과 DropZone이 어떻게하는지 연구하십시오.

원하는대로 일반 버튼의 스타일을 지정한 다음 간단한 JS 함수를 호출하여 숨겨진 입력 요소를 만들고 스타일이 지정된 버튼에 연결합니다.

<!DOCTYPE html>
<meta charset="utf-8">

<style>
    button {
        width            : 160px;
        height           : 30px;
        font-size        : 13px;
        border           : none;
        text-align       : center;
        background-color : #444;
        color            : #6f0;
    }
    button:active {
        background-color : #779;
    }
</style>

<button id="upload">Styled upload button!</button>

<script>

function Upload_On_Click(id, handler) {
    var hidden_input = null;
    document.getElementById(id).onclick = function() {hidden_input.click();}
    function setup_hidden_input() {
        hidden_input && hidden_input.parentNode.removeChild(hidden_input);
        hidden_input = document.createElement("input");
        hidden_input.setAttribute("type", "file");
        hidden_input.style.visibility = "hidden";
        document.querySelector("body").appendChild(hidden_input);
        hidden_input.onchange = function() {
            handler(hidden_input.files[0]);
            setup_hidden_input();
        };
    }
    setup_hidden_input();
}

Upload_On_Click("upload", function(file) {
    console.log("GOT FILE: " + file.name);
});

</script>

사용자가 파일을 선택할 때마다 위의 코드가 어떻게 다시 연결하는지 확인하십시오. "onchange"는 사용자가 파일 이름을 변경하는 경우에만 호출되기 때문에 중요합니다. 그러나 사용자가 파일을 제공 할 때마다 파일을 가져오고 싶을 것입니다.


CSS는 여기에서 많은 일을 할 수 있습니다 ... 약간의 속임수로 ...

<div id='wrapper'>
  <input type='file' id='browse'>
</div>

#wrapper {
     width: 93px; /*play with this value */
     height: 28px; /*play with this value */
     background: url('browseBtn.png') 0 0 no-repeat;
     border:none;
     overflow:hidden;
}

#browse{
     margin-left:-145px; /*play with this value */
     opacity:0; /* set to .5 or something so you can better position it as an overlay then back to zero again after you're done */
     -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
     filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
}

:: 참조 :: http://site-o-matic.net/?viewpost=19

-대사원


파일 버튼을 그림으로 전환하는 매우 쉬운 방법을 찾았습니다. 사진에 레이블을 지정하고 파일 버튼 위에 놓기 만하면됩니다.

<html>
<div id="File button">
    <div style="position:absolute;">
        <!--This is your labeled image-->
        <label for="fileButton"><img src="ImageURL"></label>
    </div>
    <div>
        <input type="file" id="fileButton"/>
    </div>
</div>
</html>

레이블이있는 이미지를 클릭 할 때 파일 버튼을 선택합니다.


다음은 일관된 대상 영역을 만들고 원하는대로 가짜 요소의 스타일을 지정할 수있는 간단한 CSS 전용 솔루션입니다.

기본 아이디어는 다음과 같습니다.

  1. 두 개의 "가짜"요소 (텍스트 입력 / 링크)를 실제 파일 입력의 형제로 사용합니다. 목표 영역의 상단에 정확히 위치하도록 절대적으로 배치하십시오.
  2. 파일 입력을 div로 래핑합니다. 오버플로를 숨김으로 설정하고 (파일 입력이 유출되지 않도록) 대상 영역이 원하는 크기로 정확하게 만듭니다.
  3. 파일 입력에서 불투명도를 0으로 설정하여 숨겨 지지만 여전히 클릭 할 수 있도록합니다. 대상 영역의 모든 부분을 클릭 할 수 있도록 큰 글꼴 크기를 지정하십시오.

다음은 jsfiddle입니다. http://jsfiddle.net/gwwar/nFLKU/

<form>
    <input id="faux" type="text" placeholder="Upload a file from your computer" />
    <a href="#" id="browse">Browse </a>
    <div id="wrapper">
        <input id="input" size="100" type="file" />
    </div>
</form>

모든 이전 브라우저와 새 브라우저에서 작동하는 jQuery를 사용하는 정말 영리한 솔루션을 여기서 찾았 습니다 . 실제 파일 찾아보기 버튼을 사용하여 모든 스타일링 및 click () 문제를 처리합니다. 나는 평범한 자바 스크립트 버전을 만들었다 : fiddle 해결책은 천재처럼 간단하다. 파일 입력을 보이지 않게하고 코드를 사용하여 마우스 커서 아래에 놓는다.

<div class="inp_field_12" onmousemove="file_ho(event,this,1)"><span>browse</span>
<input id="file_1" name="file_1" type="file" value="" onchange="file_ch(1)">
</div>
<div id="result_1" class="result"></div>


function file_ho(e, o, a) {
    e = window.event || e;
    var x = 0,
    y = 0;
    if (o.offsetParent) {
        do {
        x += o.offsetLeft;
        y += o.offsetTop;
        } while (o = o.offsetParent);
    }
var x1 = e.clientX || window.event.clientX;
var y1 = e.clientY || window.event.clientY;
var le = 100 - (x1 - x);
var to = 10 - (y1 - y);
document.getElementById('file_' + a).style.marginRight = le + 'px';
document.getElementById('file_' + a).style.marginTop = -to + 'px';
}

.inp_field_12 {
position:relative;
overflow:hidden;
float: left;
width: 130px;
height: 30px;
background: orange;
}
.inp_field_12 span {
position: absolute;
width: 130px;
font-family:'Calibri', 'Trebuchet MS', sans-serif;
font-size:17px;
line-height:27px;
text-align:center;
color:#555;
}
.inp_field_12 input[type='file'] {
cursor:pointer;
cursor:hand;
position: absolute;
top: 0px;
right: 0px;
-moz-opacity:0;
filter:alpha(opacity: 0);
opacity: 0;
outline: none;
outline-style:none;
outline-width:0;
ie-dummy: expression(this.hideFocus=true);
}
.inp_field_12:hover {
background-position:-140px -35px;
}
.inp_field_12:hover span {
color:#fff;
}

javascript 라이브러리를 찾는 경우-기본 솔루션은 jquery-fileinput 이 잘 작동합니다.


업데이트 하지 마십시오. 이것은 IE에서 작동하지 않거나 새로운 형제 인 FF입니다. 예상대로 다른 모든 유형의 요소에서 작동하지만 파일 입력에서는 작동하지 않습니다. 이 작업을 수행하는 훨씬 더 좋은 방법은 파일 입력과 이에 연결되는 레이블을 만드는 것입니다. 파일 입력을 표시하지 않고 붐을 일으키면 IE9 +에서 원활하게 작동합니다.

경고 :이 아래의 모든 것은 쓰레기입니다!

컨테이너에 대해 위치 / 크기 조정 된 유사 요소를 사용하면 하나의 입력 파일 (추가 마크 업 필요 없음)과 평소대로 스타일을 지정할 수 있습니다.

데모

<input type="file" class="foo">

.foo {
    display: block;
    position: relative;
    width: 300px;
    margin: auto;
    cursor: pointer;
    border: 0;
    height: 60px;
    border-radius: 5px;
    outline: 0;
}
.foo:hover:after {
    background: #5978f8;
}
.foo:after {
    transition: 200ms all ease;
    border-bottom: 3px solid rgba(0,0,0,.2);
    background: #3c5ff4;
    text-shadow: 0 2px 0 rgba(0,0,0,.2);
    color: #fff;
    font-size: 20px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    content: 'Upload Something';
    line-height: 60px;
    border-radius: 5px;
}

얘들 아!

이전 업데이트

이것을 스타일러스 믹스 인으로 바꿨습니다. 멋진 SCSS 고양이 중 한 명이 쉽게 변환 할 수 있습니다.

file-button(button_width = 150px)
  display block
  position relative
  margin auto
  cursor pointer
  border 0
  height 0
  width 0
  outline none
  &:after
    position absolute
    top 0
    text-align center
    display block
    width button_width
    left -(button_width / 2)

용법:

<input type="file">

input[type="file"]
    file-button(200px)

으로 JGuoCorySimmons이 언급 한, 당신은 덜 유연 파일 입력 요소를 숨기고하는 stylable 라벨의 클릭 동작을 사용할 수 있습니다.

<!DOCTYPE html>
<html>
<head>
<title>Custom file input</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>

<body>

<label for="upload-file" class="btn btn-info"> Choose file... </label>
<input id="upload-file" type="file" style="display: none"
onchange="this.nextElementSibling.textContent = this.previousElementSibling.title = this.files[0].name">
<div></div>

</body>
</html>

참고 URL : https://stackoverflow.com/questions/572768/styling-an-input-type-file-button

반응형