设置在按TAB键时丢失<pre>元素上的插入位置

Par*_*ris 7 jquery text append blur pre

precontentEditable="true"在我的网页,我试图使它追加"\t"当我按下<TAB>.我找到了一些其他的插件,但他们只是在工作<textarea>.

所以,问题是当我将文本追加到<pre>通过jQuery时,它会丢失插入位置.我确信它正在失去焦点,但事实并非如此.所以$("pre").focus(),什么都不做.

我试图先模糊它,但这不实用,因为插入符将根据浏览器返回不同的位置.请帮助......:P,

我的代码在这里:http://jsfiddle.net/parisk/kPRpj/

Jam*_*ury 0

首先尝试

$("pre").keydown(function(e){
    if (e.keyCode==9) {
        e.preventDefault();
        $("pre").append("\t");   
    }
});
Run Code Online (Sandbox Code Playgroud)

用于插入选项卡。它会在光标后面插入一个制表符

然后在铬合金中

var myselection = document.getSelection();
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
Run Code Online (Sandbox Code Playgroud)

在IE8中

var myselection = document.selection;
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
Run Code Online (Sandbox Code Playgroud)

最后应该让你插入符号。

(全部一起)

$("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();
         }
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑 添加测试来查看 lastChild 是否为 null 等也会更安全。另外,如果您多次使用,jQuery("pre")最好将keydown 函数放入一个变量中。jQuery(this)(这个例子就是但我太懒了)