prosource

jQuery 트리거 파일 입력

probook 2023. 9. 25. 22:50
반응형

jQuery 트리거 파일 입력

j를 를 트리거하려고 .Query를 사용하여 업로드 상자(찾아보기 버튼)를 트리거하려고 합니다.
다 입니다.

$('#fileinput').trigger('click');   

하지만 효과가 없는 것 같습니다.제발 도와주세요.감사해요.

이것은 보안 제한 때문입니다.

에 의해서만 되었습니다.<input type="file"/>로 설정됩니다.display:none;이다.visbilty:hidden.

를 를 지정하려고 .position:absolute그리고.top:-100px;그리고 그것은 효과가 있습니다

http://jsfiddle.net/DSARd/1/ 를 참조하십시오.

그것을 해킹이라 부릅니다.

그것이 당신에게 도움이 되길 바랍니다.

효과가 있었습니다.

JS:

$('#fileinput').trigger('click'); 

HTML:

<div class="hiddenfile">
  <input name="upload" type="file" id="fileinput"/>
</div>

CSS:

.hiddenfile {
 width: 0px;
 height: 0px;
 overflow: hidden;
}

>>>Cross-Browser가 작동하는 또 다른 기능:<<<

이 아이디어는 보이지 않는 거대한 "찾아보기" 단추를 사용자 정의 단추 위에 겹쳐 놓는 것입니다.따라서 사용자가 사용자 지정 버튼을 클릭하면 실제로 네이티브 입력 필드의 "찾아보기" 버튼을 클릭하게 됩니다.

JS Fiddle: http://jsfiddle.net/5Rh7b/

HTML:

<div id="mybutton">
  <input type="file" id="myfile" name="upload"/>
  Click Me!
</div>

CSS:

div#mybutton {

  /* IMPORTANT STUFF */
  overflow: hidden;
  position: relative;   

  /* SOME STYLING */
  width:  50px;
  height: 28px;
  border: 1px solid green;
  font-weight: bold
  background: red;
}

div#mybutton:hover {
  background: green;
}

input#myfile {
  height: 30px;
  cursor: pointer;
  position: absolute;
  top: 0px;
  right: 0px;
  font-size: 100px;
  z-index: 2;

  opacity: 0.0; /* Standard: FF gt 1.5, Opera, Safari */
  filter: alpha(opacity=0); /* IE lt 8 */
  -ms-filter: "alpha(opacity=0)"; /* IE 8 */
  -khtml-opacity: 0.0; /* Safari 1.x */
  -moz-opacity: 0.0; /* FF lt 1.5, Netscape */
}

자바스크립트:

$(document).ready(function() {
    $('#myfile').change(function(evt) {
        alert($(this).val());
    });
});

LABEL 요소 ex를 사용할 수 있습니다.

<div>
    <label for="browse">Click Me</label>
    <input type="file" id="browse" name="browse" style="display: none">//
</div>

입력 파일을 트리거합니다.

IE8+, 최근 FF 및 크롬에서 작동(= tested)합니다.

$('#uploadInput').focus().trigger('click');

키는 클릭을 시작하기 전에 초점을 맞추는 것입니다(그렇지 않으면 크롬이 이를 무시함).

하고 볼 수: ()).display:none 안 돼요.visibility:hidden다른 합니다.) (다른 많은 사람들이 이전에 그랬던 것처럼) 입력을 절대적으로 위치시켜 화면 밖으로 던질 것을 제안합니다.

#uploadInput {
    position: absolute;
    left: -9999px;
}

내 바이올린 좀 봐요.

http://jsfiddle.net/mohany2712/vaw8k/

.uploadFile {
  visibility: hidden;
}

#uploadIcon {
  cursor: pointer;
}
<body>
  <div class="uploadBox">
    <label for="uploadFile" id="uploadIcon">
      <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Icon_-_upload_photo_2.svg/512px-Icon_-_upload_photo_2.svg.png"  width="20px" height="20px"/>
    </label>
    <input type="file" value="upload" id="uploadFile" class="uploadFile" />
  </div>
</body>

DOM 트리에 추가하지 않고 업로드 양식과 입력 파일을 동적으로 생성하여 호기심을 유발하기 위해 원하는 작업을 수행할 수 있습니다.

$('.your-button').on('click', function() {
    let uploadForm = document.createElement('form');
    let fileInput = uploadForm.appendChild(document.createElement('input'));
    
    fileInput.type = 'file';
    fileInput.name = 'images';
    fileInput.multiple = true;

    fileInput.click();
});
    

업로드 양식을 DOM에 추가할 필요가 없습니다.

파일 입력 요소가 숨겨져 있을 때 무시되는 것에 대해 하드 디자인이 이를 못 박았습니다.또한 많은 사람들이 요소 크기를 0으로 바꾸거나 위치 조정 및 오버플로우 조정으로 요소 크기를 경계 밖으로 밀어내는 것을 확인했습니다.이것들은 모두 훌륭한 아이디어들입니다.
또한 완벽하게 작동하는 것처럼 보이는 대안적인 방법은 불투명도를 0으로 설정하는 것입니다.그러면 숨김처럼 다른 요소가 상쇄되지 않도록 항상 위치를 설정할 수 있습니다.거의 10K 픽셀에 가까운 요소를 어느 방향으로 이동시키는 것은 약간 불필요해 보입니다.

다음은 원하는 사람들을 위한 간단한 예입니다.

input[type='file']{
    position:absolute;
    opacity:0;
    /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    /* For IE5 - 7 */
    filter: alpha(opacity=0);
}

사실, 저는 이를 위한 정말 쉬운 방법을 알아냈습니다.

$('#fileinput').show().trigger('click').hide();   

이렇게 하면 파일 입력 필드에 CSS 속성표시되지 않고 거래에서 이길 수 있습니다 :)

올바른 코드:

<style>
    .upload input[type='file']{
        position: absolute;
        float: left;
        opacity: 0; /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* For IE5 - 7 */
        filter: alpha(opacity=0);
        width: 100px; height: 30px; z-index: 51
    }
    .upload input[type='button']{
        width: 100px;
        height: 30px;
        z-index: 50;
    }
    .upload input[type='submit']{
        display: none;
    }
    .upload{
        width: 100px; height: 30px
    }
</style>
<div class="upload">
    <input type='file' ID="flArquivo" onchange="upload();" />
    <input type="button" value="Selecionar" onchange="open();" />
    <input type='submit' ID="btnEnviarImagem"  />
</div>

<script type="text/javascript">
    function open() {
        $('#flArquivo').click();
    }
    function upload() {
        $('#btnEnviarImagem').click();
    }
</script>

그것은 의도적이고 계획적인 것입니다.보안 문제입니다.

JQuery 1.6.1을 사용하여 간단한 $(...)클릭()을 실행했습니다.

답변하기에는 너무 늦었지만 이 최소한의 설정이 가장 잘 맞는 것 같습니다.저도 같은 것을 찾고 있습니다.

  <div class="btn-file">
     <input type="file" class="hidden-input">
     Select your new picture
  </div>

//

.btn-file {
  display: inline-block;
  padding: 8px 12px;
  cursor: pointer;
  background: #89f;
  color: #345;
  position: relative;
  overflow: hidden;
}

.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  filter: alpha(opacity=0);
  opacity: 0;
  cursor: inherit;
  display: block;
}

jsbin

부트스트랩 파일 입력 버튼데모

이것은 매우 오래된 질문이지만 안타깝게도 이 문제는 여전히 관련성이 있으며 해결책이 필요합니다.

제가 생각해낸 (놀라울 정도로 간단한) 해결책은 실제 파일 입력 필드를 "숨긴" 후 라벨 태그(향상을 위해 부트스트랩과 HTML5를 기반으로 할 수 있음)로 포장하는 것입니다.

See here:예제코드여기

이렇게 하면 실제 파일 입력 필드가 보이지 않고 실제로 수정된 LABEL 요소인 사용자 정의된 "버튼"만 볼 수 있습니다.이 LABEL 요소를 클릭하면 파일을 선택할 수 있는 창이 뜨고 선택한 파일이 실제 파일 입력 필드로 들어갑니다.

여기에 보기와 동작을 원하는 대로 조작할 수 있습니다(예: 선택한 후 파일 입력 파일에서 선택한 파일의 이름을 가져와 어딘가에 표시).물론 LABEL 요소가 자동으로 그런 작업을 수행하는 것은 않습니다.텍스트 내용으로 LABEL(라벨) 안에 넣어두는 것이 보통입니다.

그래도 조심해요!이것의 겉모습과 행동의 조작은 여러분이 상상하고 생각할 수 있는 모든 것으로 제한됩니다. ;-);-)

아니면 간단히

$(':input[type="file"]').show().click().hide();

JQuery에서 입력 파일을 완전히 숨긴 채 클릭할 수 있습니다.

나는 이것을 사용하고 있습니다.

< input type="file" name="article_input_file" id="article_input_file" accept=".xlsx,.xls" style="display: none" >

$("#article_input_file").click();

이것은 HTML 페이지의 표준 스크립트 태그 내에서 작동합니다.

에 대한 지정 측.<input type="file"/>에게 효과가 안 @Guillaume Bodi다께)).opacity: 0;으로)

$("#MyForm").on("click", "#fake-button", function () {
        $("#uploadInput").focus().trigger("click");
    });

업로드 입력을 위한 CSS 스타일.

#uploadInput {
opacity: 0.0; 
filter: alpha(opacity=0); /* IE lt 8 */
-ms-filter: "alpha(opacity=0)"; /* IE 8 */
-khtml-opacity: 0.0; /* Safari 1.x */
-moz-opacity: 0.0;
}

한 번 해봐요, 해킹이에요.Position:절대는 Chrome, trigger('change')는 IE용입니다.

var hiddenFile = $("<input type=\"file\" name=\"file\" id=\"file1\" style=\"position:absolute;left:-9999px\" />");
$('body').append(hiddenFile);

$('#aPhotoUpload').click(function () {
    hiddenFile.trigger('click');
    if ($.browser.msie)
        hiddenFile.trigger('change');
});

hiddenFile.change(function (e) {
    alert('TODO');
});

OS 7에서는 문제가 조금 달랐습니다. FastClick이 문제를 일으켰던 것으로 드러났습니다.내가 해야 할 일은 추가하는 것이었습니다.class="needsclick"내 단추로.

브라우저 전반에 걸친 문제를 염두에 두면서 이것이 아마도 가장 좋은 답일 것입니다.

CSS:

#file {
  opacity: 0;
  width: 1px;
  height: 1px;
}

JS:

$(".file-upload").on('click',function(){
   $("[name='file']").click();
});

HTML:

<a class="file-upload">Upload</a>
<input type="file" name="file">

당신의 문제를 이해할 것 같아요, 왜냐하면 저도 비슷한 점이 있거든요.그래서 태그는<label>에 대한 속성을 가지고 있습니다. 이 속성을 사용하여 type="file"로 입력을 연결할 수 있습니다.그러나 레이아웃의 일부 규칙 때문에 이 레이블을 사용하여 이 작업을 활성화하지 않으려면 이렇게 할 수 있습니다.

$(document).ready(function(){
  var reference = $(document).find("#main");
  reference.find(".js-btn-upload").attr({
     formenctype: 'multipart/form-data'
  });
  
  reference.find(".js-btn-upload").click(function(){
    reference.find("label").trigger("click");
  });
  
});
.hide{
  overflow: hidden;
  visibility: hidden;
  /*Style for hide the elements, don't put the element "out" of the screen*/
}

.btn{
  /*button style*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="main">
<form enctype"multipart/formdata" id="form-id" class="hide" method="post" action="your-action">
  <label for="input-id" class="hide"></label>
  <input type="file" id="input-id" class="hide"/>
</form>

<button class="btn js-btn-upload">click me</button>
</div>

물론 당신은 당신만의 목적과 배치를 위해 이것을 조정할 것입니다. 하지만 그것이 제가 그것을 작동시키는 더 쉬운 방법입니다!!

기욤 보디의 대답에 근거해서 이렇게 했습니다.

$('.fileinputbar-button').on('click', function() {
    $('article.project_files > header, article.upload').show();
    $('article.project_files > header, article.upload header').addClass('active');
    $('.file_content, article.upload .content').show();
    $('.fileinput-button input').focus().click();
    $('.fileinput-button').hide();
});

즉, 처음부터 숨겼다가 트리거를 위해 표시된 다음 즉시 다시 숨깁니다.

언급URL : https://stackoverflow.com/questions/793014/jquery-trigger-file-input

반응형