简体   繁体   English

拖动HTML元素时更改光标

[英]Changing cursor while dragging HTML element

I know there has been numerous similiar questions on stackoverflow, I've read several of them, but none provided there answers worked in my case. 我知道有很多关于stackoverflow的类似问题,我已经阅读了其中的几个问题,但是没有一个问题可以解决我的问题。 I want to change cursor while dragging HTML element. 我想在拖动HTML元素时更改光标。 I tried this: 我尝试了这个:

var startX = null;
var startY = null;
var element = document.getElementById('bla');

element.addEventListener('dragstart', onDragStart, true);
element.addEventListener('dragend', onDragEnd, true);
element.addEventListener('drag', onDrag, true);

function onDragStart(e){

  startX = e.screenX;
  startY = e.screenY;
  e.target.style.cursor = "move";
}

function onDrag(e){

    e.target.style.cursor = "move";
}

function onDragEnd(e){

    var style = document.defaultView.getComputedStyle(element);

  var newLeft = parseInt(style.left) + e.screenX - startX;
  var newTop = parseInt(style.top) + e.screenY - startY;

  e.target.style.left = newLeft + 'px';
  e.target.style.top = newTop + 'px';

  e.target.style.cursor = "default";
}

But it doesn't work. 但这是行不通的。 I have no idea why on earth e.target.style.cursor = "move" doesn't work. 我不知道为什么在地球上e.target.style.cursor = "move"不起作用。 I tried changing it to document.body.style.cursor = "move" , but it doesn't work either. 我尝试将其更改为document.body.style.cursor = "move" ,但它也不起作用。 Any help with solving this problem with explanation why my code doesn't work will be greatly appreciated. 对于解决此问题并提供解释为什么我的代码不起作用的任何帮助,将不胜感激。

JS Fiddle link: https://jsfiddle.net/4w20xxvp/59/ JS小提琴链接: https : //jsfiddle.net/4w20xxvp/59/

Ps. 附言 I'm looking for pure JS solution, no JQuery. 我正在寻找纯JS解决方案,而不是JQuery。 Ps2. ps2。 I couldn't get answers from to work in my case. 在我的情况下,我无法获得上班的答案。 And I don't want to use custom cursor images, just standard css ones. 而且我不想使用自定义光标图像,而只使用标准的CSS图像。

Try to preventDefault on the other drag events. 尝试防止其他拖动事件上的Default。 Also, you might want to consider adding a drop target that would handle dragover events. 另外,您可能要考虑添加将处理拖动事件的放置目标。

document.addEventListener('dragover', (e) => e.preventDefault(), true)

( Fiddle ) 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM