DIV CSS 佈局教程網

如何讓 TextArea 與輸入框的內容自動全選
編輯:關於JavaScript     

有些欄位裡放的是一段要給使用者複製的網址、邀請碼或分享連結。與其讓使用者自己拖曳選取,不如提供一個「全選」按鈕,甚至在頁面載入時就自動選好,點一下 Ctrl+C 就能帶走。

核心觀念

關鍵只有兩行:focus() 讓欄位取得焦點,select() 選中其中所有文字。兩者必須搭配使用,因為未聚焦的元素呼叫 select 在部分瀏覽器上不會有視覺回饋。

完整範例

<script type="text/javascript">
function select_field(id){
  document.getElementById(id).focus();
  document.getElementById(id).select();
}

function init(){
  select_field('text1');
}

onload = init;
</script>

<form>
This field gets selected onload:<br/>
<input type="text" name="text1" id="text1" value="some text" />
<br/>
<textarea name="textarea1" id="textarea1" rows="9" cols="50" wrap="off">
Some long content in here. abcd efgh abcd efgh abcd efgh abcd efgh
abcd efgh abcd efgh abcd efgh abcd efgh abcd efgh
</textarea>
<br/>
<input type="button" value="Select text" onclick="select_field('textarea1')">
</form>

應用建議

1. 頁面載入就自動全選,適合「推廣碼」「短網址」這類單一重點欄位;若頁面上有很多輸入框,反而容易造成誤按,此時用按鈕觸發更合適。

2. 想讓使用者「點一下就好」,可以改成監聽 onclick 事件,把 select_field 綁到欄位本身。

3. 若同時要複製到剪貼板,可再串上 document.execCommand('copy');在 HTTPS 環境下則建議改用非同步的 Clipboard API。

4. 不要忘了 readonly 屬性:搭配它可以在全選的同時避免使用者手滑改動內容。

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