我编写了一个jQuery函数,在将文本写入输入框时自动删除单引号和双引号。在Firefox中,一切都很顺利,但在Chrome中,如果你想在文本的开头添加一些内容,则不允许这样做。因为光标始终位于输入值的末尾。我不知道如何解决它。这是我的代码:
$.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);
});
};
编辑:评论后,我试过了:
$.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);
});
};
但没有改变。
答案 0 :(得分:1)
这是一个粗略的版本供您构建 - 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();
});