Click and keydown at same time for draggable jQuer

2019-03-06 04:10发布

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.

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

1条回答
太酷不给撩
2楼-- · 2019-03-06 04:42

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);
});
查看更多
登录 后发表回答