[英]How do I make the text input box cursor blink automatically when the page loads?
[英]In Javascript, how do I automatically move the cursor to the next text box when the current one is full?
假設我的網頁上有兩個HTML文本框:
<input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />
每個文本框允許用戶輸入最多五個字符。 當用戶將五個字符txt1
txt2
時,如何使用帶或不帶jQuery的Javascript自動將光標從txt1
移動到txt1
?
基本實現如下:
$('#txt1').keyup(function() {
if(this.value.length == $(this).attr('maxlength')) {
$('#txt2').focus();
}
});
但是你可能會或可能不會關心它的一些可用性微妙之處。 如果您發現上述內容不足,那么有很多jQuery插件可以幫到您。
它被稱為autotabbing,並且jquery已經有許多插件可以執行此操作。 只是谷歌吧。
如果您想知道如何操作,那么將onkeyup事件綁定到輸入。 每次釋放一個鍵時,請確保它不是一個功能鍵,例如“Tab”(您應該允許用戶“Shift + Tab”或“Tab”到輸入而不用它然后自動接收到下一個字段。)
然后,如果輸入值的長度超過輸入的maxlength屬性,則將焦點設置在下一個輸入上(在jQuery中, $currentInput.next('input').focus()
。
這些解決方案都不能直接使用Javascript ...這個片段是一個開始:
document.getElementById('txt1').onkeydown = function() {
if (this.value.length == this.maxLength)
document.getElementById('txt2').focus();
}
但是一旦輸入了數字,就無法返回並編輯它,因為只要你點擊刪除,它就會跳回到txt2。
唯一要改變的是改為使用onkeyup 。 :d
jQuery對於它所使用的絕大多數事物都是過度和懶惰的編程,這是一個很好的例子。 除非你已經在頁面上使用它,否則對於這么小的任務來說,這是一個非常大的開銷。
JQuery插件:
https://github.com/Mathachew/jquery-autotab
最簡單的用途:
將類自動添加到輸入中。
$('.autotabbed').autotab();
我們的想法是處理keydown
事件並檢查是否已達到最大長度; 如果是這樣,請關注下一個控件。
document.getElementById('txt1').onkeydown = function() {
if (this.value.length == this.maxLength)
document.getElementById('txt2').focus();
}
您可以通過復制類來使用jQuery UI :focusable
選擇器:
$.extend($.expr[':'], {
focusable: function(element) {
var nodeName = element.nodeName.toLowerCase(),
tabIndex = $.attr(element, 'tabindex');
return (/input|select|textarea|button|object/.test(nodeName)
? !element.disabled
: 'a' == nodeName || 'area' == nodeName
? element.href || !isNaN(tabIndex)
: !isNaN(tabIndex))
// the element and all of its ancestors must be visible
// the browser may report that the area is hidden
&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
}
});
然后你可以像這樣處理它:
$(document).ready(function() {
$('input[type=text]').keydown(function() {
var $this = $(this),
$focusables = $(':focusable'),
current = $focusables.index(this),
$next;
if ($this.val().length == $this.attr('maxlength')) {
$next = $focusables.eq(current+1).length ?$focusables.eq(current+1) : $focusables.eq(0);
$next.focus();
}
});
});
在這里查看一個工作示例:
這個解決方案允許反向標簽....
$("#txt1").on('input', function () {
if (this.value.length == this.maxLength) {
$('#txt2').focus();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.