JSFiddle - React, Tailwind, and code Playground
HTML
<div class="boundary">
<img class="drag-elem" src="http://gtms03.alicdn.com/tps/i3/T1K2GLFyRXXXXKa4be-670-490.jpg">
</div>
<div class="boundary">
<div class="drag-elem"></div>
</div>
CSS
body { margin: 0; padding: 0; }
.boundary {
margin: 50px auto;
width: 300px;
height: 300px;
border: 1px solid red;
position: relative;
overflow: hidden;
}
div.drag-elem {
position: absolute;
left: 50px;
top: 50px;
z-index: 999;
width: 200px;
height: 50px;
cursor: move;
background-color: #ccc;
border: 5px solid green;
font-size: 24px;
line-height: 50px;
text-align: center;
}
.drag-elem {
cursor: move;
}
JavaScript
$.fn.extend({
/**
* Autor: 博客园华子yjh update 2014/03/02
*/
drag: function(options) {
var dragStart, dragMove, dragEnd,
$boundaryElem, b_width, b_height,
limitObj, isBeyond, diffX, diffY,
win_width = $(window).width(),
win_height = $(window).height();
function _initOptions() {
var noop = function(){}, defaultOptions;
defaultOptions = { // 默认配置项
boundaryElem: 'body', // 边界容器
isLimit: false // 是否限制拖动范围
};
options = $.extend( defaultOptions, options || {} );
// 边界元素及其宽高
$boundaryElem = $(options.boundaryElem);
b_width = $boundaryElem.innerWidth();
b_height = $boundaryElem.innerHeight();
dragStart = options.dragStart || noop,
dragMove = options.dragMove || noop,
dragEnd = options.dragEnd || noop;
}
function _drag(e) {
var clientX, clientY, offsetLeft, offsetTop, width, height,
$target = $(this), self = this;
// 记录鼠标按下时的位置及拖动元素的相对位置
clientX = e.clientX;
clientY = e.clientY;
offsetLeft = this.offsetLeft;
offsetTop = this.offsetTop;
width = $target.outerWidth();
height = $target.outerHeight();
limitObj = {
_left: 0,
_top: 0,
_right: (b_width || win_width) - width,
_bottom: (b_height || win_height) - height
};
// 拖动元素是否超出了限制边界
isBeyound = width > b_width && height > b_height;
if (isBeyound) {
diffX = b_width - width;
diffY = b_height - height;
}
dragStart.apply(this, arguments);
$(document).bind('mousemove', moveHandle)
.bind('mouseup', upHandle);
// 鼠标移动事件处理
function...