将“dragstart”事件附加到“mouseup”以获得可拖动的体验
问题描述:
寻找在“mouseup”事件之后拖动元素的解决方案。将“dragstart”事件附加到“mouseup”以获得可拖动的体验
正如你所知道的拖动发生时,它会收到“mousedown”和“mousemove”事件。
如何通过“mouseup”事件实现拖动? (点击实现时)?
https://codepen.io/pklauzinski/pen/rxroyL
// Implement drag and drop for the image
$('.box').on('mousedown', function(e) {
var $this = $(this),
$window = $(window),
mouseX = e.pageX,
mouseY = e.pageY,
width = $this.outerWidth(),
height = $this.outerHeight()
elemX = $this.offset().left + width - mouseX,
elemY = $this.offset().top + height - mouseY;
e.preventDefault();
$window.on('mousemove.drag', function(e2) {
$this.offset({
left: e2.pageX + elemX - width,
top: e2.pageY + elemY - height
});
}).one('mouseup', function() {
$window.off('mousemove.drag');
});
});
答
您可以随时使用$('.box').on('click', function(e) {
方法......,可以做到,但要记住,你将不得不添加其他用户点击或双击禁用,也,这是相当怪异的行为
示例说明
// Implement drag and drop for the image
$('.box').on('click', function(e) {
var $this = $(this),
$window = $(window),
mouseX = e.pageX,
mouseY = e.pageY,
width = $this.outerWidth(),
height = $this.outerHeight()
elemX = $this.offset().left + width - mouseX,
elemY = $this.offset().top + height - mouseY;
e.preventDefault();
$window.on('mousemove.drag', function(e2) {
$this.offset({
left: e2.pageX + elemX - width,
top: e2.pageY + elemY - height
});
}).one('mousedown', function() {
$window.off('mousemove.drag');
});
});
这是我会怎么做,虽然
// Implement drag and drop for the image
$('.box').on('mousedown', function(e) {
var $this = $(this),
$window = $(window),
mouseX = e.pageX,
mouseY = e.pageY,
width = $this.outerWidth(),
height = $this.outerHeight()
elemX = $this.offset().left + width - mouseX,
elemY = $this.offset().top + height - mouseY;
e.preventDefault();
$window.on('mousemove.drag', function(e2) {
$this.offset({
left: e2.pageX + elemX - width,
top: e2.pageY + elemY - height
});
}).one('click', function() {
$window.off('mousemove.drag');
});
});
问题是为什么?这对于大多数用户来说是意想不到的行为,您将如何停止拖动? – adeneo
我会停止拖动“mousedown”。 –
但是,当鼠标再次被释放时,这是一个点击,并拖动回来。除非按下鼠标按钮,否则总是有可拖动的东西似乎很奇怪。 – adeneo