如何在鼠标停机时永久执行一个功能,直到鼠标启动?

时间:2012-04-13 05:44:08

标签: javascript jquery

我有以下旋转图像的功能

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);
}

然而,当我以下面的方式调用它时,它只在mousedown上执行一次。

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

我的目的是让图像在被抓取时旋转,直到用户放开鼠标点击。有没有使用外部库的简单方法呢?

3 个答案:

答案 0 :(得分:1)

示例:

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);   
});

答案 1 :(得分:0)

你需要在你mousedown时使用setInterval重复调用一些代码,并在你mouseup时取消它。

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

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

答案 2 :(得分:0)

    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。因此停止旋转。

当我需要在鼠标停止时在画布上绘制时,我使用相同的技术绘制我的绘图应用程序。 希望它有所帮助:)