简体   繁体   English

在内容可编辑的表格中使用箭头键移动

[英]Move with arrow keys in a contenteditable table

How to move with UP , DOWN , LEFT , RIGHT keyboard arrows in the cells of a <table> which is contenteditable ? 如何与UP,DOWN,LEFT移动,RIGHT键盘箭头a的细胞<table>这是contenteditable

Is this possible with CSS? CSS有可能吗? Does one need Javascript for this? 为此需要Javascript吗?

 <table> <tr><td contenteditable>A1</td><td contenteditable>A2</td><td contenteditable>A3</td><td contenteditable>A4</td></tr> <tr><td contenteditable>A1</td><td contenteditable>A2</td><td contenteditable>A3</td><td contenteditable>A4</td></tr> <tr><td contenteditable>A1</td><td contenteditable>A2</td><td contenteditable>A3</td><td contenteditable>A4</td></tr> <tr><td contenteditable>A1</td><td contenteditable>A2</td><td contenteditable>A3</td><td contenteditable>A4</td></tr> </table> 

EDIT last post would not work on contenteditable table. 编辑最后一个帖子不适用于contenteditable表。

This triggers focus and moves left,right,up & down. 这会触发焦点并向左,向右,向上和向下移动。

Here's a link to the jsFiddle: https://jsfiddle.net/ytfLxxes/1/ 这是jsFiddle的链接: https ://jsfiddle.net/ytfLxxes/1/

var active = 0;


$(document).keydown(function(e){
    reCalculate(e);
    rePosition();
    return false;
});

$('td').click(function(){
   active = $(this).closest('table').find('td').index(this);
   rePosition();
});


function reCalculate(e){
    var rows = $('#navigate tr').length;
    var columns = $('#navigate tr:eq(0) td').length;
    //alert(columns + 'x' + rows);

    if (e.keyCode == 37) { //move left or wrap
        active = (active>0)?active-1:active;
    }
    if (e.keyCode == 38) { // move up
        active = (active-columns>=0)?active-columns:active;
    }
    if (e.keyCode == 39) { // move right or wrap
       active = (active<(columns*rows)-1)?active+1:active;
    }
    if (e.keyCode == 40) { // move down
        active = (active+columns<=(rows*columns)-1)?active+columns:active;
    }
}

function rePosition(){
    $('.active').removeClass('active');
    $('#navigate tr td').eq(active).addClass('active').trigger( "focus" );
    scrollInView();
}

function scrollInView(){
    var target = $('#navigate tr td:eq('+active+')');
    if (target.length)
    {
        var top = target.offset().top;

        $('html,body').stop().animate({scrollTop: top-100}, 400);
        return false;
    }
}

Do you need javascript for this, you can use jquery for that and check if the key pressed was arrow key. 您是否需要使用javascript,可以使用jquery并检查所按的键是否为箭头键。

The keyup event is very useful in this situation. 在这种情况下, keyup事件非常有用。

Then, after arrow key was pressed, you must navigate from js and put the cursor in the correct td with conteneditable. 然后,在按下箭头键之后,您必须从js导航,并将光标放置在正确的td并具有可编辑性。

I hope will be useful, best regards. 希望对您有所帮助。 Leo 狮子座

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM