JSFiddle - React, Tailwind, and code Playground
HTML
<div id="boundary">
<div id="resize-box">
<span class="cursor-north"></span>
<span class="cursor-south"></span>
<span class="cursor-west"></span>
<span class="cursor-east"></span>
<span class="cursor-north-west"></span>
<span class="cursor-north-east"></span>
<span class="cursor-south-west"></span>
<span class="cursor-south-east"></span>
</div>
</div>
CSS
body { margin: 0; padding: 0; }
#boundary {
position: relative;
width: 500px;
height: 500px;
border: 1px solid blue;
margin: 100px auto 0;
}
#resize-box {
position: absolute;
left: 200px;
top: 200px;
width: 200px;
height: 200px;
border: 1px solid #000;
}
.cursor-north,
.cursor-south,
.cursor-west,
.cursor-east,
.cursor-north-west,
.cursor-north-east,
.cursor-south-west,
.cursor-south-east {
width: 7px;
height: 7px;
background-color: red;
position: absolute;
}
.cursor-north { cursor: n-resize; left: 50%; margin-left: -3px; top: -4px; }
.cursor-south { cursor: s-resize; left: 50%; margin-left: -3px; bottom: -4px; }
.cursor-west { cursor: w-resize; left: -4px; top: 50%; margin-top: -3px; }
.cursor-east { cursor: e-resize; right: -4px; top: 50%; margin-top: -3px; }
.cursor-north-west { cursor: nw-resize; left: -4px; top: -4px; }
.cursor-north-east { cursor: ne-resize; right: -4px; top: -4px; }
.cursor-south-west { cursor: sw-resize; left: -4px; bottom: -4px; }
.cursor-south-east { cursor: se-resize; right: -4px; bottom: -4px; }
JavaScript
$.fn.extend({
/**
* Autor: 博客园华子yjh 2014/02/21
*/
drag: function(options) {
var dragStart, dragMove, dragEnd,
$boundaryElem, limitObj;
function _initOptions() {
var noop = function(){}, defaultOptions;
defaultOptions = { // 默认配置项
boundaryElem: 'body' // 边界容器
};
options = $.extend( defaultOptions, options || {} );
$boundaryElem = $(options.boundaryElem);
dragStart = options.dragStart || noop,
dragMove = options.dragMove || noop,
dragEnd = options.dragEnd || noop;
}
function _drag(e) {
var clientX, clientY, offsetLeft, offsetTop,
$target = $(this), self = this;
limitObj = {
_left: 0,
_top: 0,
_right: ($boundaryElem.innerWidth() || $(window).width()) - $target.outerWidth(),
_bottom: ($boundaryElem.innerHeight() || $(window).height()) - $target.outerHeight()
};
// 记录鼠标按下时的位置及拖动元素的相对位置
clientX = e.clientX;
clientY = e.clientY;
offsetLeft = this.offsetLeft;
offsetTop = this.offsetTop;
dragStart.apply(this, arguments);
$(document).bind('mousemove', moveHandle)
.bind('mouseup', upHandle);
// 鼠标移动事件处理
function moveHandle(e) {
var x = e.clientX - clientX + offsetLeft;
var y = e.clientY - clientY + offsetTop;
$target.css({
left: Math.max( Math.min(x, limitObj._right), limitObj._left) + 'px',
top: Math.max( Math.min(y, limitObj._bottom), limitObj._top) + 'px'
});
dragMove.apply(self, arguments);
// 阻止浏览器默认行为(鼠标在拖动图片一小段距离,会出现一个禁止的小提示,即:图片不能再拖动)
...