问题描述
我正在创建一个将元素向右移动的指令.每次点击时,项目都会向右移动,但我希望只要我按住按钮,元素就会移动.
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);
}
};
})
那么我怎样才能检测到每半秒按下按钮的时间并再次调用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?
这里有一个交互式演示:http://jsfiddle.net/vtortola/2m8vD/
There is a interactive demo here: http://jsfiddle.net/vtortola/2m8vD/
我不能为此使用 jQuery,但我可以使用 AngularJS 模块,例如 ngTouch 或其他任何东西.
I cannot use jQuery for this, but I may use AngularJS modules like ngTouch or whatever.
推荐答案
@Aaronias 让我走上正轨,向他致敬.
@Aaronias put me in the right track, kudos to him.
我设法在按住按钮时实现平滑移动,并在鼠标移出时实现可取消.关键是移除 CSS 转换,开始一个间隔做小步,然后在 mouseout 或 mouseup 上取消那个间隔.
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);
这是它工作的示例版本:http://jsfiddle.net/vtortola/2m8vD/22/
This is the version of the example where it works: http://jsfiddle.net/vtortola/2m8vD/22/
这篇关于按下按钮时触发点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!