有些輸入框(例如分享連結、優惠序號)的內容,使用者往往希望能一鍵全選以便複製。本文示範如何用一小段 JavaScript,讓文本框在獲得焦點時自動選中裡面的全部內容。
做法非常直覺:為輸入框綁定 onfocus 事件,在觸發時呼叫該元素的 select() 方法即可。這樣一來,只要使用者點擊或 Tab 進入該欄位,內容就會自動被反白選取。
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>select文件</title>
<script language="javascript" type="text/javascript">
function getFocus() {
document.getElementById("test").select();
}
</script>
</head>
<body>
<form id="f1">
<input type="text" id="test" name="test" value="你好嗎?"
onfocus="getFocus();" />
</form>
</body>
</html>
這個小技巧在「複製專用輸入框」上特別實用,能明顯提升使用者體驗。若想更進一步,還可以在 select() 之後搭配 document.execCommand('copy')(需注意瀏覽器相容性與使用者手勢限制)來實現一鍵複製。希望本文對大家的 JavaScript 開發有所幫助。