在最近的項目中,H5需要實現查看圖片和刪除圖片的效果,總結如下:
一、查看圖片
查看圖片使用weui的gallery。首先添加gallery的html,然后隱藏。
<div class="weui-gallery" style="display: none"> <span class="weui-gallery__img"> <img> </span> <div class="weui-gallery__opr"> </div> </div>
當點擊圖片位置時,若是默認圖片,則觸發上傳,否則把圖片的src放到gallery中,然后gallery顯示出來。
當gallery被點擊時則隱藏gallery,從而實現了查看圖片的效果。
// 放大圖片 var $avatar = $(".frontPic"); //圖片列表 var $galleryImg = $(".weui-gallery__img img");//相冊圖片地址 var $gallery = $(".weui-gallery"); $gallery.on("click", function(){ $gallery.fadeOut(100); }); // 上傳圖片 $(".frontPic").click(function(){ if($(".frontPic").attr("src") == "../../images/front.png"){ $(".frontPicUploader").trigger("click") }else{ $galleryImg.attr("src", $avatar.attr("src")); $gallery.fadeIn(100); } })
效果:
普通狀態:
查看圖片:
二、刪除圖片
設置好刪除圖標的樣式。
.delete-img{ width: 0.75rem !important; height: 0.75rem !important; position: absolute; float: right; left: 7.3rem; margin-top: -.2rem; display: none; }
增加刪除圖標的html。
<img src="../../images/delImg@3x.png" class="delete-img">
當加載圖片和上傳完圖片時顯示刪除圖標。
$(".delete-img").css("display","inline")
當刪除圖片時恢復默認圖片,隱藏圖標。
//刪除照片 $(".delete-img").click(function(){ $(".frontPic").attr("src","../../images/front.png") $(".delete-img").css("display","none") })
效果:
無圖片時:
有圖片時: