jQuery拖放 [英] jQuery drag and draw
本文介绍了jQuery拖放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个jQuery插件,该插件可让您拖动和绘制一个矩形(或带边框的div),但是我不确定该怎么做.我不知道目前有没有这种能力的人,所以我不知道在哪里可以找到如何做到这一点的例子.
I'm trying to build a jQuery plugin that allows you to drag and draw a rectangle (or a div with a border) but I'm not sure how to do it. I don't know of any that currently have this ability so I don't know where to look for an example of how to do this.
如何在jQuery中实现拖放?
How can I implement drag and draw in jQuery?
推荐答案
考虑到这样的事情,其基础非常简单:
The basics for something like this are quite simple, when you think about it:
- 侦听某些容器(可能是整个文档)上的
mousedown
事件;- 使用来自
event
对象(e.pageX
和e.pageY
)的鼠标坐标,将绝对定位的元素放置在鼠标的位置; - 开始侦听
mousemove
事件以更改width
和height
对象(基于鼠标坐标);
- Listen for
mousedown
events on some container (possible the entire document);- Place an absolutely positioned element at the position of the mouse, using the mouse coordinates from the
event
object (e.pageX
ande.pageY
); - Start listening to
mousemove
events to change thewidth
andheight
object (based on the mouse coordinates);
上述绝对放置的元素是例如带有边框和
background: transparent
的<div>
.The aforementioned absolute placed element is, e.g., a
<div>
with a border andbackground: transparent
.更新:这是一个示例:
$(function() { var $container = $('#container'); var $selection = $('<div>').addClass('selection-box'); $container.on('mousedown', function(e) { var click_y = e.pageY; var click_x = e.pageX; $selection.css({ 'top': click_y, 'left': click_x, 'width': 0, 'height': 0 }); $selection.appendTo($container); $container.on('mousemove', function(e) { var move_x = e.pageX, move_y = e.pageY, width = Math.abs(move_x - click_x), height = Math.abs(move_y - click_y), new_x, new_y; new_x = (move_x < click_x) ? (click_x - width) : click_x; new_y = (move_y < click_y) ? (click_y - height) : click_y; $selection.css({ 'width': width, 'height': height, 'top': new_y, 'left': new_x }); }).on('mouseup', function(e) { $container.off('mousemove'); $selection.remove(); }); }); });
演示: http://jsbin.com/ireqix/226/
这篇关于jQuery拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Place an absolutely positioned element at the position of the mouse, using the mouse coordinates from the
- 使用来自
查看全文