jquery-ui - 取消拖动转义键

时间:2014-01-09 05:59:17

标签: javascript jquery html css jquery-ui

我有一个可拖动的div列表和一个可放置的区域。使用鼠标在chrome,FF和IE9中拖拽正常工作正常。我想添加键盘交互。

当使用按div键时,拖动esc应该还原为列表。所以首先我这样做了:

        $(document).keyup( function( e ){
            e.preventDefault();
            console.log(':::keypress:::',e);
            if( e.which=== 27 || e.keyCode === 27 ){                            
                        $( '.ui-draggable-dragging' ).draggable( 'option',  'revert', 'invalid' ).trigger( 'mouseup' );                            
                    }                 
        } );

上面的代码检测到esc按键,但如果div超过可放置区域,则esc会丢失。它不会在$( document ).keyup( function( e ){ //e.preventDefault(); var mouseMoveEvent, offScreen=-50000; console.log(':::event:::',e); if( e.which=== 27 || e.keyCode === 27 ) { console.log(':::into esc keyup:::'); mouseMoveEvent = document.createEvent("MouseEvent"); offScreen = -50000; mouseMoveEvent.initMouseEvent( "mousemove", //event type : click, mousedown, mouseup, mouseover, etc. true, //canBubble true, //cancelable window, //event's AbstractView : should be window 1, // detail : Event's mouse click count offScreen, // screenX offScreen, // screenY offScreen, // clientX offScreen, // clientY false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 0, // button : 0 = click, 1 = middle button, 2 = right button null // relatedTarget : Only used with some event types (e.g. mouseover and mouseout). // In other cases, pass null. ); document.dispatchEvent(mouseMoveEvent); $( '.ui-draggable-dragging' ).draggable( 'option', 'revert', 'invalid' ).trigger( 'mouseup' ); //}else{ // if (document.createEventObject){ // mouseMoveEvent = document.createEventObject (document.event); // document.fireEvent(mouseMoveEvent); // $( '.ui-draggable-dragging' ).draggable( 'option', 'revert', 'invalid' ).trigger( 'mouseup' ); // } //} } }); 按键时恢复。所以我确实喜欢here

document.createEventObject

这在Chorme中运行良好。但这在IE和FF中不起作用。 即使我尝试使用document.fireEvent()div进行IE浏览。但它仍然不起作用。

如何在esc键上恢复Chrome,IE和FF中的可拖动{{1}} ?????

3 个答案:

答案 0 :(得分:5)

我需要相同的功能,我拿走了你所拥有的东西,这就是我使用的东西,它在最新版本的IE,FireFox和Chrome中完美适用于我。

处理ESC键

$( document ).keyup( function( e ) {
    if( e.which=== 27 || e.keyCode === 27 ) {
        $( '.ui-draggable-dragging' ).draggable({'revert': true }).trigger( 'mouseup' );
    }
});

我将此添加到我的可拖动元素

    $(".draggable-design-part").draggable({
        containment: "parent",
        scroll: true, 
        scrollSensitivity: 100,
        scrollSpeed: 100,
        snap: true,
        stop: function() {
            // Set all draggable parts back to revert: false
            // This fixes elements after drag was cancelled with ESC key
            $(".draggable-design-part").draggable("option", {revert: false });
        }
    });

答案 1 :(得分:3)

此代码适用于我:

 var ddm = $.ui.ddmanager.current;
 if ( ddm ) {
     ddm.cancel();
 }

答案 2 :(得分:0)

尝试这种方式。

$(window).keydown(function (e) {
    if (e.keyCode == 27) {
        $(document).trigger("mouseup")
    }
});