js獲取input上傳的圖片並預覽


html 部分:

<div class="upload-pics-item small">
         <span class="iconfont upload-icon icon-xiangji f-20"></span>
         <input type="file" name="pic1" value="" class="upload-pic-input">
         <p class="f-12">添加圖片</p>
          <img src="" alt="">
</div>

js 部分:

let dom = document.getElementsByClassName('upload-pic-input');
Array.from(dom).forEach(item=>{
  item.onchange = function(){
    $(this).parent().find('p').hide();
    $(this).parent().find('.iconfont').hide();
    let src = getObjectURL(this.files[0]);
    if(src){
      $(this).parent().find('img').attr('src',src);
    }else{
      $(this).parent().find('img').attr('alt',this.files[0]);
    }
  }
})

// 判斷瀏覽器是否支持 createObjectURL api
function getObjectURL(file) {  
		 var url = null;   
		 if (window.createObjectURL!=undefined) {  
		  url = window.createObjectURL(file) ;  
		 } else if (window.URL!=undefined) { // mozilla(firefox)  
		  url = window.URL.createObjectURL(file) ;  
		 } else if (window.webkitURL!=undefined) { // webkit or chrome  
		  url = window.webkitURL.createObjectURL(file) ;  
		 }  
		 return url ;  
}


免責聲明!

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



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