programing

JavaScript에서 파일 입력 요소에 대해 "클릭" 이벤트를 프로그래밍 방식으로 실행할 수 있습니까?

sourcetip 2022. 10. 2. 23:28
반응형

JavaScript에서 파일 입력 요소에 대해 "클릭" 이벤트를 프로그래밍 방식으로 실행할 수 있습니까?

클릭 이벤트 발화를 하고 싶다.<input type="file">프로그래밍 방식으로 태그를 지정합니다.

click()을 호출하는 것만으로 아무것도 할 수 없거나 적어도 파일 선택 대화상자가 뜨지 않습니다.

청취자를 사용하여 이벤트를 캡처하고 리다이렉트하는 실험을 하고 있지만, 누군가가 클릭하는 것처럼 실제로 이벤트를 진행하도록 할 수 없었습니다.

나는 오늘 하루 종일 해결책을 찾고 있었다.그리고 제가 내린 결론은 다음과 같습니다.

  1. 보안상의 이유로 Opera 및 Firefox에서는 파일 입력을 트리거할 수 없습니다.
  2. 유일한 편리한 대안은 "숨김" 또는 "표시: 없음!"이 아닌 불투명도를 사용하여 "숨김" 파일 입력을 만든 후 "아래에" 단추를 만드는 것입니다.이와 같이 버튼은 표시되지만 사용자가 클릭하면 실제로 파일 입력이 활성화됩니다.

이것이 도움이 되기를! :)

<div style="display: block; width: 100px; height: 20px; overflow: hidden;">
<button style="width: 110px; height: 30px; position: relative; top: -5px; left: -5px;"><a href="javascript: void(0)">Upload File</a></button>
<input type="file" id="upload_input" name="upload" style="font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity=0);  position: relative; top: -40px;; left: -20px" />
</div>

모든 브라우저에서 이 작업을 수행할 수는 없습니다. IE에서는 허용되지만 Mozilla 및 Opera에서는 허용되지 않습니다.

GMail에서 메시지를 작성하면 IE 및 이를 지원하는 브라우저에 대해 '첨부 파일' 기능이 한 가지 방법으로 구현되고 Firefox 및 지원하지 않는 브라우저에도 다른 방식으로 구현됩니다.

왜 그렇게 할 수 없는지는 모르겠지만 보안상의 위험이며 브라우저에서는 할 수 없는 것 중 하나는 HTML File 요소에 파일 이름을 프로그래밍 방식으로 설정하는 것입니다.

임의의 브라우저에서 클릭()을 실행할 수 있지만 브라우저에 따라서는 요소를 표시하고 초점을 맞춰야 합니다.jQuery의 예를 다음에 나타냅니다.

$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();

'가죽'보다에 있는 ''과 잘 요.click()show method show 、 「 show show show show 」를 나타냅니다.오페라IE/FF/사파리/크롬이게 도움이 됐으면 좋겠어요.

가능: FF4+, Opera?, Chrome: 단,

  1. inputElement.click()사용자 작업 컨텍스트에서 호출해야 합니다(스크립트 실행 컨텍스트가 아님).

  2. <input type="file" />한다inputElement.style.display !== 'none' 수 '은 숨길 수 없습니다

라벨 태그를 사용하면 입력을 숨길 수 있으며 관련 라벨 https://developer.mozilla.org/fr/docs/Web/HTML/Element/Label에서 작업할 수 있습니다.

보이지 않는 양식을 링크 위에 덮어써야 한다는 것을 이해하지만, 쓰기 귀찮은 사람들을 위해 제가 쓴 것입니다.저한텐요, 하지만 나누는 게 낫죠.댓글은 환영입니다.

HTML(어디선가):

<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>

HTML(상관없는 장소):

<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
    </form>
</div>

JavaScript:

function pageY(el) {
    var ot = 0;
    while (el && el.offsetParent != el) {
        ot += el.offsetTop ? el.offsetTop : 0;
        el = el.offsetParent;
    }
    return ot;
}

function pageX(el) {
    var ol = 0;
    while (el && el.offsetParent != el) {
        ol += el.offsetLeft ? el.offsetLeft : 0;
        el = el.offsetParent;
    }
    return ol;
}

function fileMove() {
    if (navigator.appName == "Microsoft Internet Explorer") {
        return; // Don't need to do this in IE. 
    }
    var link = document.getElementById("fileLink");
    var form = document.getElementById("uploadForm");
    var x = pageX(link);
    var y = pageY(link);
    form.style.position = 'absolute';
    form.style.left = x + 'px';
    form.style.top = y + 'px';
}

function fileBrowse() {
    // This works in IE only. Doesn't do jack in FF. :( 
    var browseField = document.getElementById("uploadForm").file;
    browseField.click();
}

다음 솔루션을 사용해 보십시오.http://code.google.com/p/upload-at-click/

「 」를 clickChrome, Firefox 등에서 작업하는 방법에서는 다음 스타일을 입력 파일에 적용합니다.하게 숨겨져 있을 야, 네가 것 display: none;

#fileInput {
    visibility: hidden;
    position: absolute;
    top: 0;
    left: -5000px;
}

그렇게 간단해, 내가 테스트 해봤어!

$(document).one('mousemove', function() { $(element).trigger('click') } );

비슷한 문제에 부딪혔을 때, 그건 평범한 eRube Goldberg에요.

현용 솔루션

이 오래된 게시물에 덧붙이자면, 제가 사용하던 운영 솔루션은 새로운 브라우저와 오래된 브라우저 모두에서 80% 이상에서 작동합니다.

솔루션은 복잡하지만 단순합니다.첫 번째 단계는 CSS를 사용하여 불투명도가 0인 입력 파일타입을 "under-elements"로 위장하는 것입니다.다음 단계는 JavaScript를 사용하여 필요에 따라 라벨을 업데이트하는 것입니다.

HTML ID는 특정 요소에 빠르게 액세스하려면 단순히 삽입되지만 클래스는 이 프로세스 전체를 셋업하는 CSS와 관련되어 있기 때문에 필수입니다.

<div class="file-input wrapper">
    <input id="inpFile0" type="file" class="file-input control" />
    <div class="file-input content">
        <label id="inpFileOutput0" for="inpFileButton" class="file-input output">Click Here</label>
        <input id="inpFileButton0" type="button" class="file-input button" value="Select File" />
    </div>
</div>

CSS Keep in mind, coloring and font-styles and such are totally your preference, if you use this basic CSS, you can always use after-end mark up to style as you please, this is shown in the jsFiddle listed at the end.

.file-test-area {
    border: 1px solid;
    margin: .5em;
    padding: 1em;
}
.file-input {
    cursor: pointer !important;
}
.file-input * {
    cursor: pointer !important;
    display: inline-block;
}
.file-input.wrapper {
    display: inline-block;
    font-size: 14px;
    height: auto;
    overflow: hidden;
    position: relative;
    width: auto;
}
.file-input.control {
    -moz-opacity:0 ;
    filter:alpha(opacity: 0);
    opacity: 0;

    height: 100%;
    position: absolute;
    text-align: right;
    width: 100%;
    z-index: 2;
}
.file-input.content {
    position: relative;
    top: 0px;
    left: 0px;
    z-index: 1;
}
.file-input.output {
    background-color: #FFC;
    font-size: .8em;
    padding: .2em .2em .2em .4em;
    text-align: center;
    width: 10em;
}
.file-input.button {
    border: none;
    font-weight: bold;
    margin-left: .25em;
    padding: 0 .25em;
}

자바스크립트 다만, Netscrape 2와 같이, 일부의 낡은(사용이 끝난) 브라우저는 아직 문제가 있는 경우가 있습니다.

var inp = document.getElementsByTagName('input');
for (var i=0;i<inp.length;i++) {
    if (inp[i].type != 'file') continue;
    inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];
    inp[i].onchange /*= inp[i].onmouseout*/ = function () {
        this.relatedElement.innerHTML = this.value;
    };
};

jsFiddle의 동작 예

동작:

Firefox 및 Opera에서는 보안상의 이유로 클릭 온 파일 입력을 실행할 수 없지만 MouseEvents를 사용하여 시뮬레이션을 수행할 수 있습니다.

<script>
click=function(element){
    if(element!=null){
        try {element.click();}
        catch(e) {
            var evt = document.createEvent("MouseEvents");
            evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
            element.dispatchEvent(evt);
            }
        }
    };
</script>

<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">

오래된 솔루션이라는 것은 알고 있습니다.이러한 솔루션은 모두 브라우저의 보안 주의사항에 대한 해킹이며, 진정한 가치가 있습니다.

즉, 현재 fileInput.click()은 현재 Chrome(36.0.1985.125m) 및 현재 Firefox ESR(24.7.0)에서는 동작하지만 현재 IE(11.0.9600.17207)에서는 동작하지 않습니다.버튼 위에 불투명도 0이 있는 파일 필드를 오버레이하는 것은 가능하지만, 링크 요소를 가시적인 트리거로 하고 싶었기 때문에 어떤 브라우저에서도 언더라이닝이 잘 작동하지 않습니다.점멸한 후 사라집니다.아마도 브라우저는 호버 스타일링이 실제로 적용되는지 여부를 심사숙고하고 있을 것입니다.

하지만 모든 브라우저에서 작동하는 솔루션을 찾았습니다.모든 브라우저의 모든 버전을 테스트했다고 주장하거나 영원히 작동할 것이라고는 말할 수 없지만, 지금은 제 요구를 충족시키는 것 같습니다.

간단한 조작: 파일 입력 필드를 화면 밖에 배치하고(위치: 절대, 상단: -5000px), 라벨 요소를 붙여 파일 필드 자체 대신 라벨에서 클릭을 트리거합니다.

라벨의 클릭 메서드를 호출하려면 링크를 스크립트로 작성해야 합니다.라벨 요소 내의 텍스트를 클릭할 때와 같이 자동으로 작성되지 않습니다.링크 요소가 클릭을 캡처하고 라벨에 전달되지 않는 것 같습니다.

또한 필드가 오프스크린이기 때문에 현재 선택된 파일을 표시하는 방법은 제공되지 않습니다.파일이 선택되면 바로 제출하고 싶었기 때문에 문제 없습니다만, 상황이 다르다면 조금 다른 방법이 필요합니다.

JS Fielle: http://jsfiddle.net/eyedean/1bw357kw/

popFileSelector = function() {
    var el = document.getElementById("fileElem");
    if (el) {
        el.click();  
    }
};

window.popRightAway = function() {
    document.getElementById('log').innerHTML += 'I am right away!<br />';
    popFileSelector();
};

window.popWithDelay = function() {
    document.getElementById('log').innerHTML += 'I am gonna delay!<br />';
    window.setTimeout(function() {
        document.getElementById('log').innerHTML += 'I was delayed!<br />';
        popFileSelector();
    }, 1000);
};
<body>
  <form>
      <input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" />
  </form>
  <a onclick="popRightAway()" href="#">Pop Now</a>
    <br />
  <a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a>
    <div id="log">Log: <br /></div>
</body>

이 암호는 나에게 효과가 있다.이게 네가 하려는 거야?

<input type="file" style="position:absolute;left:-999px;" id="fileinput" />
<button  id="addfiles" >Add files</button>

<script language="javascript" type="text/javascript">
   $("#addfiles").click(function(){
      $("#fileinput").click();
   });
</script>

jQuery 및 jQuery-ui를 사용하는 Safari용 솔루션:

$("<input type='file' class='ui-helper-hidden-accessible' />").appendTo("body").focus().trigger('click');

다음은 이 문제에 대한 순수한 JavaScript 솔루션입니다.모든 브라우저에서 정상 작동

<script>
    function upload_image_init(){
        var elem = document.getElementById('file');
        if(elem && document.createEvent) {
           var evt = document.createEvent("MouseEvents");
           evt.initEvent("click", true, false);
           elem.dispatchEvent(evt);
        }
    }
</script>

이벤트를 컨트롤로 리다이렉트하는 방법도 있지만 브라우저는 보안상의 이유로 이벤트를 차단하려고 하기 때문에 화재 진압에 쉽게 이벤트를 발생시킬 수 있을 것으로 예상은 하지 마십시오.

사용자가 어떤 항목을 클릭할 때 파일 대화 상자만 표시하면 되는 경우, 예를 들어 파일 업로드 버튼을 더 보기 좋게 하려면 Shaun Inman이 생각해낸 내용을 볼 수 있습니다.

키 다운, 키 누르기, 키 업의 이벤트 사이에서 컨트롤의 범위 내에서 또는 컨트롤에서 벗어나도록 창의적으로 초점을 이동함으로써 키보드의 트리거링을 실현할 수 있었습니다.YMMV

브라우저 비호환성의 세계이기 때문에 이 문제는 내버려 두는 것이 좋습니다.브라우저의 마이너 업데이트도 경고 없이 트릭을 차단할 수 있으며, 계속 작동하기 위해 해킹을 재창조해야 할 수 있습니다.

조금 전에 파일 대화상자를 열고 바로 업로드를 시작할 수 있는 커스텀 버튼을 만들고 싶어서 조사했습니다.파이어폭스는 업로드에서 아무 곳이나 클릭하면 대화 상자가 열리는 것 같습니다.따라서 다음과 같이 할 수 있습니다.

  1. 파일 업로드 및 버튼으로 사용할 이미지를 포함하는 개별 요소를 만듭니다.
  2. 겹치도록 배치하고 파일 요소의 배경 및 테두리를 투명하게 하여 단추만 표시되도록 합니다.
  3. 버튼/파일 입력 클릭 시 IE가 대화상자를 열 수 있도록 Javascript 추가
  4. 파일을 선택할 때 변경 이벤트를 사용하여 양식을 제출합니다.

이미 다른 방법으로 문제를 해결했기 때문에 이것은 이론적인 것일 뿐이지만 효과가 있을지도 모릅니다.

저는 한 잔 했다.<input type="button">태그는 표시되지 않습니다.제가 한 일은 그 파일을"onClick"라벨 등 모든 유형의 가시 컴포넌트에 대한 이벤트입니다.이 작업은 Google Chrome의 Developer Tools 또는 Mozilla Firefox의 Firebug에서 마우스 오른쪽 버튼 클릭 "edit HTML" 명령을 사용하여 수행되었습니다.이 이벤트에서는 다음 스크립트 또는 이와 유사한 스크립트를 지정합니다.

JQuery가 있는 경우:

$('#id_of_component').click();

그렇지 않은 경우:

document.getElementById('id_of_component').click();

감사해요.

이 솔루션은 효과가 있습니다.다운로드에는 MSBLOB를 사용해야 합니다.

$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
   var fileName = invoiceNumberEntity + ".pdf";
   var pdfDownload = document.createElement("a");
   document.body.appendChild(pdfDownload);

   AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
       var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
       if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
           window.navigator.msSaveBlob(fileBlob, fileName);
       } else { // for other browsers
           var fileURL = window.URL.createObjectURL(fileBlob);
           pdfDownload.href = fileURL;
           pdfDownload.download = fileName;
           pdfDownload.click();      
       }
   });
};

각도JS 또는 일반 Javascript의 경우에도 마찬가지입니다.

이것은 이제 Firefox 4에서 가능하지만 팝업창으로 간주되므로 팝업창이 열릴 때마다 차단됩니다.

여기 나에게 도움이 되는 솔루션이 있습니다: CSS:

#uploadtruefield {
    left: 225px;
    opacity: 0;
    position: absolute;
    right: 0;
    top: 266px;
    opacity:0;
    -moz-opacity:0;
    filter:alpha(opacity:0);
    width: 270px;
    z-index: 2;
}

.uploadmask {
    background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
    width:132px;
}

HTML ('작은' JQuery 도움말 포함) :

<div class="uploadmask">
    <input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield"  type="file" onchange="$('#uploadmaskfield').val(this.value)" >

마스크가 제대로 된 업로드 필드로 충분히 커버되어 있는지 확인합니다.

조작은 <a> 태그의 [파일 열기]대화상자에서 응답에 따라 실행할 수 있습니다.

<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px;     height: 1px" multiple />
<a href="" onclick="document.getElementById('upload').click(); return false">Upload</a>

입력(파일)이 형식을 벗어나면 클릭 이벤트를 실행하면 파일 대화상자가 호출됩니다.

이게 도움이 됐으면 좋겠는데 - 두 시간 동안 머리를 부딪혔어요.

IE8이나 IE9에서는 어떤 식으로든 javascript를 사용하여 파일 입력을 열게 되면(다 시도해 봤다고 믿어도), javascript를 사용하여 폼을 제출할 수 없게 되어, 사일런트하게 실패합니다.

통상의 송신 버튼을 사용해 폼을 송신하면, 동작하는 경우가 있습니다만, form.submit(); 를 호출하면 자동적으로 실패합니다.

선택 파일 버튼을 투명 파일 입력으로 덮어써야 했습니다.

이 방법은 효과가 있었습니다.

<script>
    function sel_file() {
        $("input[name=userfile]").trigger('click');
    }  
</script>

<input type="file" name="userfile" id="userfile" />

<a href="javascript:sel_file();">Click</a>

불가능하지 않습니다.

var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);  
setTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);

다만, 클릭 이벤트로 호출된 기능에 있는 경우에만 동작합니다.

따라서 다음과 같은 설정이 있을 수 있습니다.

html:

<div onclick="openFileChooser()" class="some_fancy_stuff">Click here to open image chooser</div>
<input type="file" id="input_img">

JavaScript:

    function openFileChooser() {
      var evObj = document.createEvent('MouseEvents');
      evObj.initMouseEvent('click', true, true, window);  
      setTimeout(function()
      { 
        document.getElementById('input_img').dispatchEvent(evObj);      
      },100);      
    }

사용할 수 있습니다.

<button id="file">select file</button>
<input type="file" name="file" id="file_input" style="display:none;">
<script>
$('#file').click(function() {
        $('#file_input').focus().trigger('click');
    });
</script>

이렇게 하려면 파일 입력 위에 보이지 않는 패스스루 요소를 클릭합니다.

function simulateFileClick() {
  const div = document.createElement("div")
  div.style.visibility = "hidden"
  div.style.position = "absolute"
  div.style.width = "100%"
  div.style.height = "100%"
  div.style.pointerEvents = "none"
  const fileInput = document.getElementById("fileInput") // or whatever selector you like
  fileInput.style.position = "relative"
  fileInput.appendChild(div)
  const mouseEvent = new MouseEvent("click")
  div.dispatchEvent(mouseEvent)
}

언급URL : https://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input

반응형