按下按钮时触发点击事件 [英] Trigger click events while button is pressed

查看:129
本文介绍了按下按钮时触发点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个将元素向右移动的指令.每次单击时,该项目都会移到右侧,但是我希望只要按住按钮就可以移动元素.

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,但可以使用ngTouch之类的AngularJS模块或其他工具.

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过渡,开始执行一些小步骤,并在将其移出或移入鼠标时取消该间隔.

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/

这篇关于按下按钮时触发点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆