在每个字符

时间:2015-07-03 12:52:09

标签: jquery

这是与我所制作的代码相关的错误。

我正在制作文本长度验证字段,想出了某种工作代码。但是,我在这里做的事情是每次键入时都会导致文本光标向左移动,这意味着您键入的文本会向后或混乱。

下面发生了什么可能导致这种情况? 我想象可能是拼接?

JSFiddle和jQuery下面的

$(function(){

    var charLimit = 10;

    $('.input').keypress(function(e){
        if (e.which > 0){
            var string = $(this).text().split("");
            for(i=0;i<charLimit;i++){
                if(string[i] !== undefined){
                    string.splice((charLimit-1),0,"<span class='error'>");
                    string.push("</span>");
                }
            }
            $(this).html(string.join(""));
        }
    });

});

1 个答案:

答案 0 :(得分:3)

使用此功能始终将光标置于末尾:

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

之后使用它
 $(this).html(string.join(""));
像这样:

 placeCaretAtEnd( document.getElementById(".input") );

您可能正在寻找:http://jsfiddle.net/nh9hbxdf/

这可以通过使用一些css技巧来实现:

这是更新的代码:

 <p id="output"></p>
 <textarea></textarea>
<style>
  textarea, #output {
                width: 500px;
                height: 10em;
                padding: 0.2em;
                margin: 0.2em;
                box-sizing: border-box;
                font: 13px arial;
                border: 1px solid silver;
                white-space: pre-wrap;
            }

            textarea {
                position: relative;
                -webkit-text-fill-color: transparent;
                overflow: auto;
            }

            #output {
                position: absolute;
                pointer-events: none;
                z-index: 1;
            }

            #output span:first-of-type {
                color: red;
                /*background-color: blue;*/
            }
.error{
    color:red;
}

<script>

 $(document).ready(function(){
                $('textarea').on('input', function() {
                    $('#output').html(this.value.replace(/^(.{10})(.*)$/, '$1<span class="error" contenteditable>$2</span>'));
                });

                $('textarea').focus();
            });     

</script>