Archive

2012年1月 的Archive

[jQuery] drag image in div (仿facebook編輯大頭圖)

2012年1月19日 尚無評論

在玩facebook時,覺得他的編輯大頭圖及編輯動態時報的大banner滿好玩的

索性也來玩一下,基本的DEMO在這邊

http://rdandy.tw/imagemagick/drag.php

CSS:

<style type="text/css">
<!--
body {
	margin:0;
}
#container {
	width:300px;
	height:300px;
	border:0;
	margin:0;
	padding:0;
	position: relative;
}
#smallwindow {
	overflow:hidden;
	width:300px;
	height:300px;
	position: relative;
	border:0;
	margin:0;
	padding:0;
	cursor:move;
}
#dragimage {
	position:relative;
	border:0;
}
-->
</style>

HTML body:

<input type="text" id="x" value="">
<input type="text" id="y" value="">
<input type="text" id="w" value="">
<input type="text" id="h" value="">
<br />
crop left: <input type="text" id="realleft" value="">
crop top: <input type="text" id="realtop" value="">
<table>
  <tr>
    <td>拖拉圖</td>
    <td><div id="smallwindow" align="center"><img src="yaya.jpg" id="dragimage" draggable="false" onclick="javascript:return false;" onmousedown="javascript:return false;" onmouseup="javascript:return false;" /></div></td>
  </tr>
</table>

JavaScript:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() 
{
	var max_size = 1920;
	var smallwindow = $("#smallwindow");
	var smallwindowwidth = smallwindow.width();
	var smallwindowheight = smallwindow.height();
	var smallwindowleft = smallwindow.offset().left;
	var smallwindowtop = smallwindow.offset().top;
	
    var imgwidth = $("#dragimage").width();
	var imgheight = $("#dragimage").height();
	
	var limitleft = smallwindowleft - (imgwidth - smallwindowwidth);
	var limittop = smallwindowtop - (imgheight - smallwindowheight);
	var limitright = smallwindowleft;
	var limitbottom = smallwindowtop;

	$("#dragimage").draggable({containment:[limitleft,limittop,limitright,limitbottom]});
	
	$("#dragimage").mouseup(function() {
		//var pos = $("#dragimage").position();
		
		var offset = $("#dragimage").offset();
  		$("#x").val(offset.left - smallwindowleft);
		$("#y").val(offset.top - smallwindowtop);
		$("#w").val($("#dragimage").width());
		$("#h").val($("#dragimage").height());
  		$("#realleft").val((offset.left - smallwindowleft) * -1);
		$("#realtop").val((offset.top - smallwindowtop) * -1);
	});
	
	var rleft = smallwindowleft - ((imgwidth - smallwindowwidth) / 2);
	var rtop = smallwindowtop - ((imgheight - smallwindowheight) / 2);
	$("#dragimage").offset({left: rleft, top:rtop })
	
});

</script>
Categories: JavaScript, 程式設計 Tags: ,