How to implement mouse drag in javascript?

I need to implement mouse resistance in javascript.

As an example of what I mean, think about how the Enligthenment window manager handles the edge resistance of the screen to switch between different desktops or if you are not familiar with this:

imagine a large rectangle with a square inside it. when clicking [onmousedown] inside a square, the mouse allows you to move to the borders of the square, and then performs some resistance until a threshold value is reached, and then moves within the larger rectangle.

Ideally, the mouse cursor should remain trapped inside the square until this threshold is met, and only leave this area if it is encountered.

Any ideas or examples of this somewhere? A cruciform solution is also of great importance. (up to ie7, that is) Thank you!

+3
source share
1 answer

As indicated, you cannot set the mouse position using Javascript.

Since you asked about implementing this on mousedown, I assume the user is dragging something onto the screen. That way you can make the element they drag show this behavior. You need two elements in order to act as regions where you can freely drag the target and the other to determine the size of the border. I would do it with jQuery to shorten the code, but basically you will have something like this. (Unverified code)

HTML:

<div class='borderLand'>
    <div class='freeZone'>
        <img class='draggable'>
    </div>
</div>

CSS

.borderLand {position: relative; width: 110px; height: 110px;}
.freeZone {position: relative; top: 10px; left:10px; height: 100px; width: 100px;}

JS:

, -

onmousedown{
  check for click location
  if it over the draggable (watch for bubbling) begin dragging, set dragging flag
}

onmouseup{
  clear dragging flag if it set
}

borderland onmouseover{
  if dragging, stop the movement of the draggable (watch for bubbling here too)
}

borderland onmouseout{
  start dragging again (if they move back in or out it doesn't matter, you want to drag)
}

, , JS , , .

+3

Source: https://habr.com/ru/post/1762488/


All Articles