自动填充文本框第一个字母,用户可以在文本框中输入剩余字母。但是用户不应该删除页面加载时填充的第一个字母。用户可以使用退格键删除他写的字母,删除或选择除填充的第一个字母以外的所有字母。
<input type="text" id="nameId" value="Given Name"/>
$("#nameId").on("keydown", function(e) {
if (($(this).get(0).selectionStart == 0 && (e.keyCode < 35 || e.keyCode > 40))
|| ($(this).get(0).selectionStart == 1 && e.keyCode == 8)) {
return false;
}
});
$("#nameId").bind("contextmenu", function(e) {
e.preventDefault();
});
fiddle ,除了选定的删除外,它很好。
答案 0 :(得分:4)
$('#text').on('select keydown contextmenu mousedown drop', function(e) {
if(e.type == 'keydown' && this.selectionStart == 0 && this.selectionEnd == 0) {
this.setSelectionRange(1, 1);
}
if((e.keyCode == 37 && (this.selectionStart == 1 || e.ctrlKey)) || (e.keyCode == 36) ||
(e.keyCode == 8 && this.value.length == 1)|| (e.keyCode == 46 && this.selectionStart == 0) || e.type == 'drop') {
e.preventDefault();
}
if(this.selectionStart == 0 &&
this.selectionStart != this.selectionEnd) {
this.setSelectionRange(1, this.selectionEnd);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="text" value="N" />
&#13;
答案 1 :(得分:2)
检查此DEMO
HTML
<input type="text" id="text" value="N" />
Jquery
$(document).ready(function(){
var prefix = "N";
var ctrlDown = false,shiftDown = false;
var ctrlKey = 17, aKey = 65 , shiftKey = 16,rKey = 39,lKey = 37;
// mange ctrl and shift key event make flag true/false
$(document).keydown(function(e)
{
if (e.keyCode == ctrlKey) ctrlDown = true;
if (e.keyCode == shiftKey) shiftDown = true;
}).keyup(function(e)
{
if (e.keyCode == ctrlKey) ctrlDown = false;
if (e.keyCode == shiftKey) shiftDown = false;
});
// if ctrl and shift flag ture and press A or right arrow key or left arrow key it return falsel
$(document).on('keydown','#text',function(e){
if (ctrlDown && (e.keyCode == aKey) || shiftDown && ((e.keyCode == rKey)) || shiftDown && (e.keyCode == lKey)) return false;
});
$(document).on('keyup','#text',function(e){
// if useing right key move cursor to first position it auto move focus at last character in text box
if(e.keyCode == rKey || e.keyCode == lKey){
if(this.selectionStart == 0){
this.selectionStart = this.selectionEnd = $('#text').val().length;
}
}
if($.trim($(this).val()).length === 0){
$(this).val(prefix);
}
});
// using mouse click on to first position it auto move focus at last character in text box
$("#text").on("contextmenu click", function(e) {
this.selectionStart = this.selectionEnd = $('#text').val().length;
e.preventDefault();
});
// using mouse click select all text it auto move focus at last character in text box
$( "#text" ).select(function() {
this.selectionStart = this.selectionEnd = $('#text').val().length;
});
});