点击小图,显示大图

1.html

<img class="pimg" src="1.jpg" width="200px"/>
<div id="BigImg">
	<div id="BigDiv">
		<img id="bigImg" src=""/>
	</div>
</div>

2.css

#BigImg{
	display: none;
	position:fixed;
	top:0;
	left:0;
	width:100%;
	height:100%;
	background:rgba(0,0,0,.5);
}
#BigDiv{
	position:absolute;
}

3.js

$(function(){
	$(".pimg").click(function(){
		var _this = $(this);
		showBigImg("#BigImg","#BigDiv","#bigImg", _this);
	})
			
	function showBigImg(BigImg,BigDiv,bigImg,_this){
		//获取img的src属性
		var src = _this.attr("src");
				
		//获取当前图片的宽高
		var width = _this.width();
		var height = _this.height();
				
		//获取屏幕的宽高
		var screenWidth = $(window).width(); 
		var screenHeight = $(window).height(); 
		var scale = 0.8;
				
		var imgWidth,imgHeight;
				
		$(bigImg).attr("src",src);
				
		//如果图片的宽度超过屏幕的80%=>图片宽度等比例缩小、高度也跟着缩小
		if(width>screenWidth*scale){
			imgWidth = screenWidth*scale;
			imgHeight = imgWidth/width*height;
		//图片的高度超过屏幕的80%=>高度等比例缩小,宽度也跟着等比例缩小
		}else if(height>screenHeight*scale){
			imgHeight = screenHeight*scale;
			imgWidth = imgHeight/height*width;
			if(imgWidth>screenWidth*scale){
				imgWidth = screenWidth*scale;
			}
			}else{
				imgWidth = width;
				imgHeight = height;
			}
				
			console.log(screenHeight);
				
			$(bigImg).css("width",imgWidth);
			$(bigImg).css("height",imgHeight);
				
			var h = (screenHeight - imgHeight)/2;
			var t = (screenWidth - imgWidth)/2;
			$(BigDiv).css({"top":h,"left":t});
//			console.log(src);

			//背景层淡入显示
			$(BigImg).fadeIn("fast");
	}
			
			
	$("#BigImg").click(function(){
		//背景层淡出隐藏
		$("#BigImg").fadeOut("fast");
	})
})

4.效果图

posted @ 2018-08-31 15:42  董七  阅读(564)  评论(0编辑  收藏  举报