javascript 在鼠标按下期间获取鼠标位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11282366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:37:59  来源:igfitidea点击:

Get mouse location during mouse down?

javascriptjquery

提问by maxhud

How can I continuously get the position of the mouse whilst its button is being held down?

如何在按住按钮的同时连续获取鼠标的位置?

I know I can do:

我知道我可以做到:

<element onclick="functionName(event)"></element>
<script>
function functionName(e){
e.pageX
e.pageY
//do stuff
}
</script>

and I know you can use the onmousedown event, but how would I continuously get the position while the button is still held down?

我知道你可以使用 onmousedown 事件,但是我如何在按钮仍然被按住的情况下连续获得位置?

Oddly I couldn't find this anywhere I looked.

奇怪的是,我在任何地方都找不到这个。

回答by VisioN

Anyway, I'd suggest using mousemoveevent with check if whichevent property equals 1(i.e. left mouse button pressed):

无论如何,我建议使用mousemove事件检查which事件属性是否等于1(即按下鼠标左键):

$("element").on("mousemove", function(e) {
    if (e.which == 1) {
        console.log(e.pageX + " / " + e.pageY);
    }
});?

DEMO:http://jsfiddle.net/HBZBQ/

演示:http : //jsfiddle.net/HBZBQ/

回答by Bojangles

Hereis a JSFiddle for you. You need to store the state of the mouse button in a variable.

这里有一个 JSFiddle 给你。您需要将鼠标按钮的状态存储在一个变量中。

jQuery:

jQuery:

$(document).ready(function() {
    $(document).mousedown(function() {
        $(this).data('mousedown', true);
    });
    $(document).mouseup(function() {
        $(this).data('mousedown', false);
    });

    $(document).mousemove(function(e) {
        if($(this).data('mousedown')) {
            $('body').text('X: ' + e.pageX + ', Y: ' + e.pageY);
        }
    });
});?

Here, I'm storing the mouse button's up or down state in documentusing $(document).data(). I could have used a global variable, but storing it this way makes the code a little cleaner.

在这里,我将鼠标按钮的向上或向下状态存储在documentusing 中$(document).data()。我本可以使用全局变量,但是以这种方式存储它会使代码更简洁一些。

In your $.mousemove()function, only do what you want if the mouse is down. In the code above, I'm simply printing the mouse's position.

在您的$.mousemove()功能中,只有在鼠标按下时才做您想做的事情。在上面的代码中,我只是打印鼠标的位置。