5

部分 Html 代码

    <td><input type="text" name="date1" id="date1" value="<?php echo $_POST['date1']?>" size="1"></td>
    <td><input type="text" name="amount1" id="amount1" size="5"></td>

这是 javascript

<script>
$(document).ready(function(){
$('input').keyup(function(e){
if(e.which==39)
$(this).closest('td').next().find('input').focus();
else if(e.which==37)
$(this).closest('td').prev().find('input').focus();
else if(e.which==40)
$(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input').focus();
else if(e.which==38)
$(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input').focus();
});
});
</script>

当我单击输入字段 date1 并按导航键右箭头时,我进入输入字段 amount1。那没问题。

例如,如果在字段 amount1 中我输入了错误的金额并想要更正它,我尝试按导航键左箭头并想要转到必要的字符。但是我可以输入字段 date1。

问题。什么是 javascript 代码来获得类似 MS Excel 的行为(如果按 F2 然后向左/向右箭头键我向左/向右移动一个字符;如果按 Esc 键然后向左/向右箭头键我移动到下一个输入字段)?

4

1 回答 1

2

所以我使用了一个类和只读属性。代码完整注释如下:

$("input").on("click", function (event) {
    //If clicked, remove '.selected' from whoever currently has it as well as add readonly (in case someone clicks on another before pressing Enter or Esc to finish edit).
    $(".selected").removeClass("selected").attr('readonly', 'readonly');
    $(this).addClass("selected").focus(); //Add selected to the clicked one
}).keydown(function (event) {
    var key = event.keyCode || event.which;
    console.log(key);

    //If it's readonly, then you can move around
    if ($(this).attr('readonly') == "readonly") {
        if (key == 39) $(this).removeClass("selected").closest('td').next().find('input').addClass("selected").focus();
        else if (key == 37) $(this).removeClass("selected").closest('td').prev().find('input').addClass("selected").focus();
        else if (key == 40) $(this).removeClass("selected").closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').addClass("selected").focus();
        else if (key == 38) $(this).removeClass("selected").closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').addClass("selected").focus();
    }

    //If F2 was pressed
    if (key == 113) { //F2
        //Remove readonly, allow to be edited and block moving arrows (you ca use arrows to navigate through letters, like a normal input
        $(this).prop('onclick', null).removeAttr('readonly');
    } else if (key == 13 || key == 27) { //ENTER or ESC
        //Put readonly back, allow to move around
        $(this).attr('readonly', 'readonly');
    }

});

点击一个以选择它,您可以四处移动。F2 使输入可编辑,箭头作为输入的默认设置。单击另一个表,按 Enter 或 ESC 都将输入恢复为只读,移动箭头再次起作用。

见演示@jsFiddle

于 2013-05-28T13:34:05.037 回答