同时单击和按下可拖动jQuery事件的键? [英] Click and keydown at same time for draggable jQuery event?

查看:103
本文介绍了同时单击和按下可拖动jQuery事件的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图仅当Shift键处于按下状态(模仿按住状态)时满足单击条件时才触发jQuery UI事件,并且不禁用该事件.

I'm trying to have a jQuery UI event fire only if it meets the criteria of being clicked while the shift key is in the keydown state ( to mimic being held), and if not disable the event.

此示例仅在用户单击并按住shift时,才使用jQuery UI的.draggable拖动容器div.

This example uses jQuery UI's .draggable to drag a container div only if the user clicks and holds shift.

http://jsfiddle.net/zEfyC/

无法正常工作的代码,不确定这是否是执行此操作的最佳方法或出了什么问题.

Non working code, not sure if this is the best way to do this or what's wrong.

$(document).click(function(e) {

    $('.container').keydown(function() {
        if (e.shiftKey) {
            $('.container').draggable();
        } else {
            $('.container').draggable({
                disabled: true
            });
        }
    });
});​

推荐答案

我看到该代码有很多错误.首先,仅在单击文档后才添加关键侦听器.其次,您要将keydown添加到容器div中,而不是整个文档中.然后,您还需要聆听keyup,因为释放Shift键应禁用可拖动性,然后还需要将disable传递给false:在shift向下的情况下为false.并且您的处理程序缺少e参数.试试这个:

I see lots of errors with that code. Firstly, you only add the key listener after there's been a click on the document. Second you are adding keydown to the container div, rather than the whole document. Then, you also need to listen to keyup, since releasing the shift key should disable draggability, then you also need to pass disabled: false to the case where shift is down. And your handler is missing the e parameter. Try this:

$(function(e) {
    var handler = function(e) {
        if (e.shiftKey) {
            $('.container').draggable({
                disabled: false
            });
        } else {
            $('.container').draggable({
                disabled: true
            });
        }
    };
    $(document).keydown(handler);
    $(document).keyup(handler);
});

这篇关于同时单击和按下可拖动jQuery事件的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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