0

ブラウザのデフォルトの動作は、次のフォーム要素を選択することです。タブが押されたときに 4 つのスペースとしましょう。IDE でコードをインデントする場合と同様です。JavaScript でこの動作を実現するにはどうすればよいですか? jQuery を使用する必要がある場合、またはそのほうが簡単な場合は、それで問題ありません。

ありがとう!

4

1 に答える 1

1

キーコードを追跡し、要素に 4 つのスペースを追加すると、それが実行されます。タブキーが押されたときのデフォルトを防ぐことができます。そのようです?:

すべてのコメントの後に編集:

ああ、そうですね、実際にはいくつかの JS 関数を要求しています (テキスト領域でカーソル位置を取得する、テキストを変更する、テキスト領域でカーソル位置を設定する)。もう少し見回せば、これらすべてが得られるでしょうが、私はいい人なので、そこに入れておきます. その他の回答は、getCursorPosition() に関するこの投稿とsetCursorPosition() に関するこの投稿にあります。ya のためにjsFiddleを更新しました。コードの更新はこちら

<script>

    $('#myarea').on('keydown', function(e) { 
    var thecode = e.keyCode || e.which; 

    if (thecode == 9) { 
        e.preventDefault(); 
        var html = $('#myarea').val();
        var pos = $('#myarea').getCursorPosition(); // get cursor position
        var prepend = html.substring(0,pos);
        var append = html.replace(prepend,'');
        var newVal = prepend+'    '+append;
        $('#myarea').val(newVal);
        $('#myarea').setCursorPosition(pos+4);
    } 
});

new function($) {
    $.fn.getCursorPosition = function() {
        var pos = 0;
        var el = $(this).get(0);
        // IE Support
        if (document.selection) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        // Firefox support
        else if (el.selectionStart || el.selectionStart == '0')
            pos = el.selectionStart;

        return pos;
    }
} (jQuery);

new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);
​
</script>

<textarea id="myarea"></textarea>
于 2012-06-18T17:52:40.243 に答える