麻烦我的代码,我有一个“ - ”必须插入每个Enter键

时间:2013-05-30 09:59:00

标签: jquery html css

我的代码有问题,我有一个“ - ”,必须在每个Enter键上插入, 这是我的jQuery和jsfiddle:

$("#textbox").on("keydown", function(e) {
      if(e.which == 13){
        var $this = $(this);
        setTimeout(function(){
          $this.insertAtCaret("- ");
        }, 0);
      }

http://jsfiddle.net/npGVS/

提前致谢:)

1 个答案:

答案 0 :(得分:3)

insertAtCaret是jQuery的扩展,通常不在其中。如果您添加the extension,则可以使用:

DEMO

$.fn.insertAtCaret = function(myValue) {
    return this.each(function() {
        var me = this;
        if (document.selection) { // IE
            me.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            me.focus();
        } else if (me.selectionStart || me.selectionStart == '0') { // Real browsers
            var startPos = me.selectionStart, endPos = me.selectionEnd, scrollTop = me.scrollTop;
            me.value = me.value.substring(0, startPos) + myValue + me.value.substring(endPos, me.value.length);
            me.focus();
            me.selectionStart = startPos + myValue.length;
            me.selectionEnd = startPos + myValue.length;
            me.scrollTop = scrollTop;
        } else {
            me.value += myValue;
            me.focus();
        }
    });
};