Cursor position abnormally situated at the end of the input value in Chrome

I coded a jQuery function to remove automatically single and double quotes while writing text in to input box. In firefox everything goes good but in Chrome, if you want to add something beginning of the text, it is not allowed. Because the cursor always situated at the end of the input value. I don't know how I fix it. Here is my code:

$.fn.removeQuotes = function()
{
    var elem = $(this);
    elem.bind("focus propertychange change click keyup input paste", function(event)
    {
        setTimeout(function ()
        {
            elem.val(elem.val().replace(/['"]/g, ""));
        }, 1);
   });
};

EDIT: After comments, I tried this:

$.fn.removeQuotes = function()
{
    var elem = $(this);
    elem.bind("focus propertychange change click keyup input paste", function(event)
    {
        // store current positions in variables
        var start = this.selectionStart,
        end = this.selectionEnd;
        setTimeout(function ()
        {
            elem.val(elem.val().replace(/['"]/g, ""));
        }, 1);
       // restore from variables...
       this.setSelectionRange(start, end);
   });
};

But nothing changed.


这里有一个粗略的版本供您参考 - https://jsfiddle.net/Sanjeevi/79gun3g0/1/

    <div>
      <input id="text-box" type="text">
    </div>

$.fn.removeQuotes = function()
{
    var elem = $(this);
    elem.bind("keyup", function(event)
    {
                var start = elem.caret();
            console.log(start);
            elem.val(elem.val().replace(/['"]/g, ""));
            setCaretPosition('text-box',start);
   });
};

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

$(document).ready(function(){
    $("#text-box").removeQuotes();
});
链接地址: http://www.djcxy.com/p/68460.html

上一篇: f4m文档包含媒体标记中缺少的网址

下一篇: 游标位置异常位于Chrome中输入值的末尾