【JS】 偽主動觸發input:file的click事件


  大家用到input:file標簽時,對於input:file的樣式難看的處理方法一般有2種:

  1. 采用透明化input:file標簽的方法,上面放的input:file標簽,下面放的是其他標簽,實際點擊的還是上面的input:file標簽,這種方法考驗開發的樣式水平了,不在細說
  2. 采用js去控制,觸發input:file標簽的click事件。這樣就可以使用漂亮的圖案來替換input:file的位置,代碼如下:
 1 <html>
 2 <head>
 3 </head>
 4 <body>
 5     <input type="file" id="fileElem"  style="display:none" >
 6     <button href="#" id="fileSelect" onclick="openBrowse()">Select some files</button>
 7 </body>
 8 <script>
 9 
10     
11 
12     function openBrowse(){ 
13         var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false; 
14         if(ie){ 
15             
16             document.getElementById("fileElem").click(); 
17             
18         }else{
19             
20             var a=document.createEvent("MouseEvents");
21             a.initEvent("click", true, true);  
22             document.getElementById("fileElem").dispatchEvent(a);
23             
24         } 
25     } 
26 </script>
27 
28 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM