溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

HTML頁(yè)面如何實(shí)現(xiàn)上傳圖片預(yù)覽功能

發(fā)布時(shí)間:2021-10-19 16:06:51 來(lái)源:億速云 閱讀:174 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)HTML頁(yè)面如何實(shí)現(xiàn)上傳圖片預(yù)覽功能,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

近期在項(xiàng)目中遇到一個(gè)問(wèn)題,需要在上傳圖片時(shí)可以在本地預(yù)覽,但是傳統(tǒng)的'<input type="file">'并不支持。這里可以借用uploadPreview.js 實(shí)現(xiàn)

/*這部分內(nèi)容非本人原創(chuàng),完全來(lái)自網(wǎng)絡(luò),感謝原創(chuàng)作者的分享*/
jQuery.fn.extend({
    uploadPreview: function (opts) {
        var _self = this,
            _this = $(this);
        opts = jQuery.extend({
            Img: "ImgPr",
            Width: 100,
            Height: 100,
            ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
            Callback: function () {}
        }, opts || {});
        _self.getObjectURL = function (file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file)
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        };
        _this.change(function () {
            if (this.value) {
                if (!RegExp("\.(" + opts.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
                    alert("選擇文件錯(cuò)誤,圖片類型必須是" + opts.ImgType.join(",") + "中的一種");
                    this.value = "";
                    return false
                }
                if ($.browser.msie) {
                    try {
                        $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
                    } catch (e) {
                        var src = "";
                        var obj = $("#" + opts.Img);
                        var div = obj.parent("div")[0];
                        _self.select();
                        if (top != self) {
                            window.parent.document.body.focus()
                        } else {
                            _self.blur()
                        }
                        src = document.selection.createRange().text;
                        document.selection.empty();
                        obj.hide();
                        obj.parent("div").css({
                            'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
                            'width': opts.Width + 'px',
                            'height': opts.Height + 'px'
                        });
                        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
                    }
                } else {
                    $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
                }
                opts.Callback()
            }
        })
    }
});

可以把這部分js文件copy到自己的文件夾目錄里面,在jQuery文件之后引用。先來(lái)看一小段html代碼

<!--圖片預(yù)覽窗口-->
<div>
 <img id="ImgPr" width="120" height="120"/>
</div>
<!--圖片上傳-->
<input type="file" id="up" />

然后,只需要在自己的js文件中給對(duì)應(yīng)的文件上傳表單綁定uoload事件就可以

$("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120 });

看看初步的頁(yè)面效果:

HTML頁(yè)面如何實(shí)現(xiàn)上傳圖片預(yù)覽功能

在我的項(xiàng)目中,想要實(shí)現(xiàn)的效果是,點(diǎn)擊一個(gè)默認(rèn)的圖片就可以直接用新的圖片替換原來(lái)的圖片,所以需要把預(yù)覽圖片的src賦給原來(lái)的圖片,同時(shí),我還想去掉“選擇文件”和后面的文件路徑,這些東西不太美觀,所以我采取了一下的方法

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
   #up{opacity: 0; position:absolute; top:40%; left:1%;}/*把這個(gè)文件上傳表單設(shè)置全透明,藏在圖片下面,不顯示給用戶*/
  </style>
 </head>
 <body>
 <!--圖片預(yù)覽窗口-->
 <div class="ImgBox">
  <img id="ImgPr" width="120" height="120"/>
 </div>
 <!--圖片上傳-->
 <input type="file" class="up" />
 <a class="ImgChange" href="#">  <!--用這個(gè)a標(biāo)簽來(lái)替代圖片上傳表單-->
   <img src="resources/p_w_picpaths/3.jpg" alt="">
 </a>
 

 <script src="resources/js/jquery-1.8.3.min.js"></script>
 <script src="resources/js/uploadPreview.js"></script>
 <script>

  $(".up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120 });

  $('.ImgChange').click(function(e){
      e.preventDefault();//阻止a鏈接默認(rèn)跳轉(zhuǎn)

      if($('.up')){ //把圖片的點(diǎn)擊事件加到<input type="file">上
       $('.up').click();
       setInterval(function(){ //點(diǎn)擊以后加載新的文件路徑需要一段時(shí)間,所以設(shè)定1秒鐘的延時(shí),否則獲取src屬性時(shí)就是undefined
        $('.ImgChange img').attr('src',$('#ImgPr').attr('src'));
       },1000); //有效避免出現(xiàn) fakepath這種情況

      };
     }
  );

 </script>
 </body>
</html>

初步效果截圖:

HTML頁(yè)面如何實(shí)現(xiàn)上傳圖片預(yù)覽功能、

現(xiàn)在我需要在圖片上加幾個(gè)字,提示用戶點(diǎn)擊更換圖片,圖片更換以后這幾個(gè)字就跟著隱藏掉,并且去掉上面的那個(gè)圖片預(yù)覽窗口

HTML代碼

<div class="ImgBox">
  <input type="file" class="up" />
  <a class="ImgChange" href="#">
	<img id="ImgPr" src="p_w_picpaths/2.jpg" alt="默認(rèn)背景圖片" >
	<h3 class="changeImg">點(diǎn)擊更換圖片</h3>
  </a> <!-- 直接把圖片預(yù)覽的ID值付給背景圖片-->
</div>

CSS代碼

.up{opacity: 0; position:absolute; top:40%; left:20%;}
.ImgChange{display: inline-block; position:relative;}
.changeImg{position:absolute; top:0; bottom:0; left:0; right:0; margin:auto;
					width:150px; height:30px; line-height:30px; text-align:center; 
					color:#fff; background:#00B7EE; border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; -ms-border-radius:5px;}

JS代碼

$('.ImgChange').click(function(e){
        e.preventDefault();
        if($('.up')){
           $('.up').click().uploadPreview({ Img: "ImgPr", Callback: remove() });
        }; /*注意看原始的JS文件,這里還有一個(gè)回掉函數(shù)可供使用*/
    }); 
	function remove(){
		$('.changeImg').hide();
	}

那如果是想要一次上傳多張并且支持圖片預(yù)覽的話,推薦使用Web Uploader http://fex.baidu.com/webuploader/ 

HTML頁(yè)面如何實(shí)現(xiàn)上傳圖片預(yù)覽功能

那如果是圖片,并且支持本地預(yù)UploaderbUploader

關(guān)于“HTML頁(yè)面如何實(shí)現(xiàn)上傳圖片預(yù)覽功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI