如何在鼠标按下时永久执行函数,直到鼠标向上

How to perpetually execute a function while the mouse is down, until the mouse is up?

本文关键字:鼠标 函数 执行 时永      更新时间:2023-09-26

我有以下功能来旋转图像

function rotateImage(offsetSelector, xCoordinate, yCoordinate, imageSelector){
var x = xCoordinate - offsetSelector.offset().left - offsetSelector.width()/2;
var y = -1*(yCoordinate - offsetSelector.offset().top - offsetSelector.height()/2);
var theta = Math.atan2(y,x)*(180/Math.PI);        
var rotate = 'rotate(' + theta + 'deg)';
imageSelector.css('-moz-transform', rotate);
}

但是,当我以以下方式调用它时,它仅在鼠标按下时执行一次。

$('#someImage').on('mousedown', function(event){
        rotateImage($(this).parent(), event.pageX,event.pageY, $(this));    
});

我的目的是让图像在被抓取时旋转,直到用户松开鼠标单击。 有没有一种简单的方法可以在不使用外部库的情况下做到这一点?

示例:

var timer;
function rotateImageTimer(offsetSelector, xCoordinate, yCoordinate, imageSelector)
{
    timer = setInterval("rotateImage('"+offsetSelector+"', '"+xCoordinate+"', '"+yCoordinate+"', '"+imageSelector+"')", 100);
}

function rotateImage(offsetSelector, xCoordinate, yCoordinate, imageSelector){
    var x = xCoordinate - offsetSelector.offset().left - offsetSelector.width()/2;
    var y = -1*(yCoordinate - offsetSelector.offset().top - offsetSelector.height()/2);
    var theta = Math.atan2(y,x)*(180/Math.PI);        
    var rotate = 'rotate(' + theta + 'deg)';
    imageSelector.css('-moz-transform', rotate);      
}

$('#someImage').on('mousedown', function(event){
    rotateImageTimer($(this).parent(), event.pageX,event.pageY, $(this));  
});
$('#someImage').on('mouseup', function(event){
    clearIneterval(timer);   
});
当您

鼠标按下时,您需要使用 setInterval 重复调用一些代码,并在鼠标向上时取消它。

可以在此处找到一个例子:http://www.codingforums.com/showthread.php?t=166115

有关setInterval和setTimeout的一些信息:http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

    var isMouseDown = false;
$('#someImage').on('mousedown', function(event){
isMouseDown = true;
        rotateImage($(this).parent(), event.pageX,event.pageY, $(this));    
});
$('#someImage').on('mouseup', function(event){
isMouseDown = false;
});

function rotateImage(offsetSelector, xCoordinate, yCoordinate, imageSelector){
   while(isMouseDown){
 var x = xCoordinate - offsetSelector.offset().left - offsetSelector.width()/2;
    var y = -1*(yCoordinate - offsetSelector.offset().top - offsetSelector.height()/2);
    var theta = Math.atan2(y,x)*(180/Math.PI);        
    var rotate = 'rotate(' + theta + 'deg)';
    imageSelector.css('-moz-transform', rotate);    
}// end of while  
}

在上面的代码中,我有一个可变isMouseDown。当鼠标向下设置为true .虽然它是真的,但你的图像应该旋转。我也对mouseup具有约束力。当它被调用时,isMouseDown被设置为false。因此停止旋转。

当我需要在鼠标按下时在画布上绘图并在再次启动时停止时,我对我的绘图应用程序使用相同的技术。希望对:)有所帮助