许多其他使用keypress的解决方案在移动设备上不起作用,您需要使用input。
html
<input type="text" id="name" data-value="" autocomplete="off" spellcheck="true" placeholder="Type your name" autofocus />
jQuery
$('#name').on('input', function() {
var cursor_pos = $(this).getCursorPosition()
if(!(/^[a-zA-Z ']*$/.test($(this).val())) ) {
$(this).val($(this).attr('data-value'))
$(this).setCursorPosition(cursor_pos - 1)
return
}
$(this).attr('data-value', $(this).val())
})
$.fn.getCursorPosition = function() {
if(this.length == 0) return -1
return $(this).getSelectionStart()
}
$.fn.setCursorPosition = function(position) {
if(this.lengh == 0) return this
return $(this).setSelection(position, position)
}
$.fn.getSelectionStart = function(){
if(this.lengh == 0) return -1
input = this[0]
var pos = input.value.length
if (input.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', input.value.length)
if (r.text == '')
pos = input.value.length
pos = input.value.lastIndexOf(r.text)
} else if(typeof(input.selectionStart)!="undefined")
pos = input.selectionStart
return pos
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
if(this.lengh == 0) return this
input = this[0]
if(input.createTextRange) {
var range = input.createTextRange()
range.collapse(true)
range.moveEnd('character', selectionEnd)
range.moveStart('character', selectionStart)
range.select()
}
else if (input.setSelectionRange) {
input.focus()
input.setSelectionRange(selectionStart, selectionEnd)
}
return this
}