1. 程式人生 > >[jQuery]地圖瀏覽:如何實現圖片的放大縮小和點選之後的位置居中

[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;
}

最終效果:

點選放大按鈕:

點選圖片的任意位置: