replace mousemove by mousedrag?

♀尐吖头ヾ 提交于 2019-12-01 14:53:26

You want to do everything in your mousemove() only when a mouse button is being pressed, right?

$(document).ready(function() {
    var lbDown = false;

    $(".magnify").mousedown(function(e) {
        if (e.which === 1) {
            lbDown = true;
        }
    });
    $(".magnify").mouseup(function(e) {
        if(e.which === 1) {
            lbDown = false;
        }
    });

    $(".magnify").mousemove(function(e) {
        if(lbDown) {
            //your code here
        }
    });
});

We use our own variable to keep track of the left mouse button (lbDown). Set it to true on mousedown and to false on mouseup, then react to this in the mousemove()-function.

EDIT
Here's a fiddle of it.
Of course, you'll want to add some code to hide the magnifying glass once the user stopped dragging it around.

By request, here's the explanation of the logic behind it:
As JS has no native way of checking a mouse-buttons state, we need to implement this feature ourselves.
A mouse-button has two states: it's either up or down, thus we have to introduce a boolean variable to keep track of the mouse-buttons state (lbDown for left button down in my code).
Now all we have to do is set this variable according to the state. Luckily, JS provides event-handlers: mousedown gets fired once the mouse button is down (clicked) and mouseup gets fired once the user releases the clicked button. So we set our boolean variable to true in mousedown and to false in mouseup.
We may now check anywhere in the code with a simple if(lbDown) if one of the mouse buttons is currently, by the time of the check, down.

The downside is, this would - by now - be true for every mouse-button! We haven't implemented anything yet to distinguish the buttons.
Every event in JS has the property which, which lets you determine which key or button was pressed to trigger the (keyboard-/mouse-)event.
Now, when reading the jQuery API on which we read, that in case of a mouse event, which will be 1 for the left mouse button, so we add another if to mousedown and mouseup, so lbDown will only be set, when the left button is clicked.

I do not have enough reputation to comment but I wanted to add that the above code (from the correct answer) could instigate a problem. If you only want one special "thing" to for example move when dragged (for example an image to be moved with the current clientX position) it is good to go with $(document).mouseup... instead of $("thing").mouseup since you might not want to have to release your mouse button on that exact thing. This caused a problem for me and I just wanted to mention it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!