DIV CSS 佈局教程網

js 切換輸入焦點:讓游標依時間自動跳到下一個欄位
編輯:關於JavaScript     

有些互動需要「游標停留一會兒後自動跳到另一個欄位」,例如連續輸入的驗證碼格、掃碼後自動前進的序號欄。核心工具就是 focus() 加上 setTimeout。

完整範例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>js 切換游標</title>
<script type="text/javascript">
var t;
function a()
{
  document.getElementById('input1').focus();
  t = setTimeout("b()", 3000);
  // clearTimeout(t);
  // document.getElementById('input2').focus();
  // document.getElementById('input1').focus();
  }
function b()
  {
  clearTimeout(t);
  document.getElementById('input2').focus();
  }
function c()
  {
  setTimeout("document.getElementById('input3').focus()", 500);
  }
</script>
</head>
<body>
<input id="testButton" type="button" onclick="a()" value='btn1'>
<input type="text" id="input1">
<input type="text" id="input2">

<input id="testButton1" type="button" onclick="c()" value='btn2'>
<input type="text" id="input3">
</body>
</html>

程式在示範什麼

按 btn1 後,游標先落在 input1;三秒後 b() 被執行,清掉計時器並把游標移到 input2。註解掉的幾行則是另一種寫法:不用計時器,直接同步連續呼叫 focus,這種情況下只有最後一次生效,游標會停在最後被聚焦的元素上——這正好說明了「同步連續 focus」與「延遲 focus」的差別。

按 btn2 則是更精簡的版本:半秒後把游標送到 input3,展示不需要另外定義函式、直接把動作寫進 setTimeout 字串的折衷寫法。

實務上的建議

1. 別把動作寫成字串。 setTimeout(function(){ document.getElementById('input3').focus(); }, 500) 比字串版本更好除錯,也不會因為變數改名而失效。

2. 記得保留 handle。 只有留住 setTimeout 的回傳值,才能在時機不對時用 clearTimeout 取消,避免游標被莫名搶走。

3. 自動跳格要小心使用者體驗。 自動切換焦點在密碼、信用卡號這類欄位上容易造成輸入錯誤(打錯一格卻跳到下一格)。實務上更常見的做法是監聽 input 事件,確認已滿位數才前進,並在游標跳走後仍允許 Backspace 回上一格。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved