JQuery实现图片的缩放和拖拽功能
作者:陆金龙
发表时间:2014-11-12 22:59
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var isDown = false; //是否按下了鼠标
var xpos0 = 0; //鼠标按下时的横坐标位置
var ypos0 = 0; //鼠标按下时的纵坐标位置
var leftAdd = 0; //拖拽完成后的横向偏移量
var topAdd = 0; //拖拽完成后的纵向偏移量
$(function () {
//为鼠标滚轮事件注册图片缩放功能
$("#divImg").bind("mousewheel", function () {
if (event.wheelDelta > 0) {
imgToSize(10);
} else {
imgToSize(-10);
}
});
//为鼠标按下和弹起事件注册图片拖拽功能
$("#divImg").bind("mousedown", function (e) {
isDown = true;
$("#divImg").css("cursor", "pointer");
xpos = e.pageX;
ypos = e.pageY;
});
$("#divImg").bind("mouseup", function (e) {
isDown = false;
$("#divImg").css("cursor", "default");
//拖拽结束后更新偏移量
leftAdd = leftAdd + (e.pageX - xpos);
topAdd = topAdd + (e.pageY - ypos);
});
//为拖拽过程注册鼠标移动事件,实现拖拽过程中图片位置持续改变
$("#divImg").bind("mousemove", function (e) {
if (isDown) {
var leftAddTemp = leftAdd + (e.pageX - xpos);
var topAddTemp = topAdd + (e.pageY - ypos);
var img = $("#divImg img");
var left = ($("#divImg").width() - img.width()) / 2;
var top = ($("#divImg").height() - img.height()) / 2;
img.css("margin-left", left + leftAddTemp + "px").css("margin-top", top + topAddTemp + "px");
}
});
});
// 图片缩放
@param name='size':放缩百分比
function imgToSize(size) {
var img = $("#divImg img");
var oWidth = img.width(); //取得图片的实际宽度
var oHeight = img.height(); //取得图片的实际高度
img.width(oWidth + parseInt(oWidth * size / 100));
img.height(oHeight + parseInt(oHeight * size / 100));
var left = ($("#divImg").width() - img.width()) / 2;
var top = ($("#divImg").height() - img.height()) / 2;
img.css("margin-left", left + leftAdd + "px").css("margin-top", top + topAdd + "px");//缩放时保留拖拽的位置偏移
}
</script>
</head>
<body>
<div id="divImg" style="width:610px; height:570px; overflow:hidden; border:1px solid gray; vertical-align:middle; text-align:center;">
<img src="dog.jpg" />
</div>
</body>
</html>