问题
I am creating a directive that moves an element to the right. In each click, the item is moved to the right, but I would like that the element moves as long I am keeping the button pressed.
.directive("car", function(){
return {
restrict:"A",
link:function(scope,element,attrs,controller){
var left=0;
var car = angular.element(element[0].querySelector('.car'));
var move = function(e){
left+=10;
car[0].style.left = left+"px";
};
element.on("click", move);
}
};
})
So how can I detect when the button is being pressed each half second and recall the move
function again? Is it possible to have a smooth movement?
There is a interactive demo here: http://jsfiddle.net/vtortola/2m8vD/
I cannot use jQuery for this, but I may use AngularJS modules like ngTouch or whatever.
回答1:
I did a simple mockup of a way to solve you're issue using mouseup and mousedown events with the $timeout service.
.directive("car", function($timeout){
return {
restrict:"A",
link:function(scope,element,attrs,controller){
var left=0;
var car = angular.element(element[0].querySelector('.car'));
var timeout;
var moveOnce= function() {
left+=10;
car[0].style.left = left+"px";
};
var move = function(e){
$timeout.cancel(timeout);
timeout = $timeout(function(){
moveALittle();
move();
}, 250);
};
var stop = function(e){
$timeout.cancel(timeout);
};
element.on("click", moveOnce);
element.on("mousedown", move);
element.on("mouseup", stop);
element.on("$destroy",function(){
element.off("click",moveOnce);
element.off("mousedown", move);
element.off("mouseup", stop);
});
}
};
})
Here is an updated demo: http://jsfiddle.net/2m8vD/12/
You should be able to easily update the the timeout delay and pixel movement to get the movement to be as smooth as you like.
As an alternative to using the mouseup and mousedown events you can easily enough use the angular directives ng-mouseup and ng-mousedown events bound directly to the button element.
<button ng-mousedown="move" ng-mouseup="stop">Move</button>
UPDATE:
Added moveOnce() function to allow for a single click.
回答2:
@Aaronias put me in the right track, kudos to him.
I managed to achieve smooth movement when holding the button and cancellable when the mouse moves out. The key is remove the CSS transition, start an interval doing small steps and cancel that interval on mouseout or mouseup.
var move = function(e){
if(interval)
return;
step(e);
mustStop = false;
interval = $interval(function(){
step(e);
if(mustStop){
$interval.cancel(interval);
mustStop = false;
interval = null;
}
}, 10);
};
var stop = function(){ mustStop= true;};
right.on("mousedown", move)
.on("mouseup", stop)
.on("mouseout", stop);
left.on("mousedown", move)
.on("mouseup", stop)
.on("mouseout", stop);
This is the version of the example where it works: http://jsfiddle.net/vtortola/2m8vD/22/
来源:https://stackoverflow.com/questions/24640517/trigger-click-events-while-button-is-pressed