为什么dragstart中的event.preventDefault()会阻止执行拖拽事件? [英] Why is event.preventDefault() in dragstart interrupting furthur drag events from executing?

查看:1099
本文介绍了为什么dragstart中的event.preventDefault()会阻止执行拖拽事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拖动图像,为了阻止浏览器的默认图像拖动,我使用的是event.preventDefault()。但由于某种原因,它正在中断诸如dragenter,dragover,dragend等进一步的事件。为什么这样,如何在不中断正常拖动事件的情况下停止浏览器的默认功能。

I am trying to drag over an image and in order to stop the browser's default image drag, I am using event.preventDefault(). But for some reason it is interrupting further events like dragenter, dragover, dragend etc from executing. Why is this and How can I stop browser's default function without interrupting normal drag events.

<img src="/img/image1" id="img1"/>

jQuery

var obj=$('#ironman');  
obj.on('dragstart', function (e) {
      //e.preventDefault();
      console.log("dragstart");
  });

  obj.on('dragenter', function (e) {
      console.log("dragenter");
  });

  obj.on('dragover', function () {
      console.log("dragover");
  });
  obj.on('dragleave', function () {
      console.log("dragleave");
  });

  obj.on('dragend', function () {
      console.log("dragend");
  });

JSfiddle

推荐答案

这是一个艰难的因为你在元素上停止本机拖链事件。不确定为什么要这样做,但实现原生拖动的一种方法是取消它并处理鼠标事件

This is a tough one as you are stopping native drag chain event on the element. Not sure why you want to do this, but one way to implement the native dragging is to cancel it and deal with mouse events

var obj=$('#ironman');  
obj.on('mousedown', function (e) {
  console.log("mousedown");
  // bind to the mousemove event
  obj.on('mousemove', function (e) {
      console.log("mousemove");
  });
});

obj.on('mouseup', function (e) {
  console.log("mouseup");
  // unbind the mousemove event
  obj.unbind('mousemove');
});
obj.on('dragstart', function (e) {
  e.preventDefault();  // cancel the native drag event chain
  console.log("dragstart");
});

这篇关于为什么dragstart中的event.preventDefault()会阻止执行拖拽事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆