The API is introduced

document.elementFromPoint(x, y)

The elementFromPoint method returns the topmost Element at the given coordinate point.

If the specified coordinate point is outside the visual range of the document, or if both coordinates are negative, null is returned.

This is an API I found when I used to do editor requirements before, and I used it again when I used to do editor block-level element drag and drop recently. I found it very useful and could deal with many scenarios that could not be solved before, so I share it.

The basic use

function changeColor(newColor) {
  elem = document.elementFromPoint(2, 2);
  elem.style.color = newColor;
}
Copy the code

Special scenario

Here is a scenario that controls the display of the drag icon. The drag icon element is extended outside the editor, and the position is achieved by absolute positioning.

Basic idea:

When the mouse hover on the editor, the target object of the move event can find the associated block element, so that the drag icon can be located based on the block element position.

Show hide:

Another needs to consider is that when the mouse left the editable area to remove drag icon, with this demand alone in front of the train of thought will have a problem, because once the mouse left in the middle of the content area represents the technology not available according to the target to the associated block element, means that can not be sure of the drag and drop ICONS associated with the block element, You need to remove the drag icon, but the user may just want to move the mouse over the drag icon, which is awkward.

Blank area:

The other thing is that other knowledge base products actually have implementations that still show drag ICONS when I mouse over a blank area (in the red box below) or even the gray area on either side of the blank area.

ElementFromPoint + flexible handling

The most critical step, step 4, is to use the elementFromPoint method, which is a little more complicated than that, but that’s the idea.

Browser compatibility

MDN address: developer.mozilla.org/en-US/docs/…