简体   繁体   中英

HTML5 Drag and drop. Detecting where element was grabbed

I am working with HTML 5 Drag and Drop API, and implementing sortable list and auto scroll. For some of features, I would like to able to detect which part of element was grabbed

Here is the illustration

在此处输入图片说明

Any help would be appreciated, thanks

You can use the computed padding+width of the element and the offsetX property of the MouseEvent to calculate the selected region.

yourElement.addEventListener('mousedown', function onDragStart(event){
  let width = parseInt(window.getComputedStyle(yourElement).getPropertyValue('width'));
  let padding = parseInt(window.getComputedStyle(yourElement).getPropertyValue('padding-left'));
  let position = event.offsetX;
  let middle = (width / 2) + padding;

  if (position <= middle) {
    console.log('left');
  } else {
    console.log('right');
  }
});

See this jsfiddle for an example: https://jsfiddle.net/c23Lu6gy/28/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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