まずやってみる
$("pre").keydown(function(e){
if (e.keyCode==9) {
e.preventDefault();
$("pre").append("\t");
}
});
タブを挿入します。カーソルの後にタブが挿入されます
次にクロームで
var myselection = document.getSelection();
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
IE8で
var myselection = document.selection;
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
最後にキャレットを取得する必要があります。
(一同)
$("pre").keydown(function(e){
if (e.keyCode==9) {
e.preventDefault();
$("pre").append("\t");
var myselection = null;
if(document.getSelection)
{
myselection = document.getSelection();
}
else if (document.selection)
{
myselection = document.selection;
}
if(myselection != null)
{
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
}
}
});
編集
lastChild が null であるかどうかなどを確認するテストを追加する方が安全です。また、keydown関数でjQuery("pre")
はjQuery(this)
、複数回使用している場合は変数に入れてください。(これは例ですが、私は怠け者です)