Home >Web Front-end >JS Tutorial >JavaScript implementation of mouse drag element example code_javascript skills
1. Foreword
The first purpose of implementing mouse dragging elements is to drag many small dots on a page for fixed positioning, and then copy the HTML and paste it into the development code of the page. This is such a function, and it has achieved a lot I have done it all over the place, but I have no choice but to use the jQuery.fn.draggable plug-in. After contacting some information and other people’s ideas, I finally perfected this dragging function today. Let’s take a look at its implementation
2. Design Ideas
Bind the mouse down event to the drag element, bind the mouse movement and mouse up events to the document object;
Why not bind all three events to the drag element? This is because Mouse move and pop up event handlers will not execute when the mouse moves too fast
$(document)
.bind('mousemove', fn)
.bind('mouseup', fn);
3. Source code implementation details
There are many things worth noting in the implementation source code:
1. First, in the mouse press event, when clicking and dragging the element, the area text may be selected. This is not what we need. The solution is as follows:
2. If the dragging element is a picture (img tag) and the mouse drags the picture a short distance, a small forbidden prompt will appear, that is: the picture cannot be dragged anymore.
This is the browser's default behavior, so just block the browser default behavior
3. Issues about boundaries (handling drag range)
The code implemented at the beginning is as follows:
if ( x >= limitObj._left && x <= limitObj._right ) {
$target.css({ left: x 'px' });
}
if ( y >= limitObj._top && y <= limitObj._bottom ) {
$target.css({ top: y 'px' });
}
Further thinking: Why does the above problem occur? The reason is that the variable x may be smaller than limitObj._left or larger than limitObj._right. The same is true for the variable y.
So the code needs to be processed as follows:
Finally solved this problem, but cloudgamer gave a better way of writing:
Complete program source code:
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);
// 阻止浏览器默认行为(鼠标在拖动图片一小段距离,会出现一个禁止的小提示,即:图片不能再拖动)
e.preventDefault();
);
}
_initOptions(); // Initialize the configuration object
$(this)
.css({ position: 'absolute' })
$(this).bind('mousedown', function(e){
_drag.apply(this, [e]); // for firefox ie9 || less than ie9
window.getSelection? window.getSelection(). AllRanges(): document.selection.empty(); ; 🎜> });
Instance call:
Copy code
The code is as follows:
// Call instance
(function(){$('.drag-elem').drag({