Click and keydown at same time for draggable jQuery event?

前提是你 提交于 2019-12-02 20:22:49

问题


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:


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


来源:https://stackoverflow.com/questions/9899466/click-and-keydown-at-same-time-for-draggable-jquery-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!