[jQuery]地图浏览:如何实现图片的放大缩小和点击之后的位置居中

HTML代码:

 

<!DOCTYPE html>
<html>
	<head>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
        <link rel="stylesheet" href="style.css" type="text/css" />
        <script type='text/javascript' src='script.js'></script>
	</head>

	<body>
	
	<img id="back" name="back" src="back.jpg" alt = "背景"/>

	<div>
		<div id="larger" class="size_btn"><img src="+.png" alt="+"></div>
		<div id="smaller" class="size_btn"><img src="-.png" alt="+"></div>
	</div>

	</body>
</html>


JS代码:

 

 

$(document).ready(function(){

	/******** 先将图片居中并完全显示 ********/
	var proportion = 1;
	if($(window).width() / $('#back').width() < $(window).height() / $('#back').height())
		proportion = $(window).width()/$('#back').width();
	else
		proportion = $(window).height()/$('#back').height();
	
	var back_width = $('#back').width() * proportion;
	var back_height = $('#back').height() * proportion;
	var back_left = ($(window).width() - back_width)/2;
	var back_top = ($(window).height() - back_height)/2;
	$('#back').width(back_width);      
	$('#back').height(back_height);
	$("#back").offset({left:back_left,top:back_top});


	//放大缩小操作时的尺寸变化
	var sizeX = back_width/10;
	var sizeY = back_height/10;
	//放大缩小操作时的位置变化
	var moveX = sizeX/2;
	var moveY = sizeY/2;

	//点击放大按钮
	$('#larger').click(function(){
		$('#back').height("+=" + sizeX);      
		$('#back').width("+=" + sizeY);
		$("#back").offset(function(n,c){
			newPos = new Object();
			newPos.left = c.left-moveX;
			newPos.top = c.top-moveY;
			return newPos;
		});
	});

	//点击缩小按钮
	$('#smaller').click(function(){
		$('#back').height("-=" + sizeX);      
		$('#back').width("-=" + sizeY);
		$("#back").offset(function(n,c){
			newPos = new Object();
			newPos.left = c.left + moveX;
			newPos.top = c.top + moveY;
			return newPos;
		});
	});

	//点击图片
	$('#back').click(function(event){
		var x=($(window).width()/2) - event.clientX + $("#back").offset().left;
		var y=($(window).height()/2) - event.clientY + $("#back").offset().top;
		$("#back").animate({left:x,top:y});
	});
});

 

 

css代码:

 

#back{
	left: 0px;
    top:  0px;
	position:absolute;
	z-index:-1;
}

.size_btn{
	position:absolute;
	height:30px;
	width:30px;
}

#larger{
}

#smaller{
	top:60px;
}

 

最终效果:

 


点击放大按钮:


点击图片的任意位置:


 

posted @ 2013-06-29 21:51  jlins  阅读(2178)  评论(0编辑  收藏  举报