JavaScript文字框指令碼編寫的注意事項,javascript文字框

來源:互聯網
上載者:User

JavaScript文字框指令碼編寫的注意事項,javascript文字框

在HTML中,有兩種方式來表現文字框:

一種是使用input元素的單行文本,另一種是使用textarea的多行文字框。

使用input方式,必須添加type,設定為“text”。

  • size特性,可以指定文字框內能夠顯示的字元數。
  • value屬性可以設定文字框的初始值。
  • maxlength特性則是用於指定文字框內可以接受的最大字元數。

textarea的初始值則必須放在開始和結束標籤之內。

  • cols是文字框字元行數;
  • rows是文字框字元列數;

另外,不能在HTML中給textarea指定最大字元數;

一、選擇文本

上述兩種文字框都支援

  • select()方法,這個方法主要用於選擇文字框中的所有文本。不接受任何參數。
  • 與這個方法對應的select事件,在選擇了文字框中的文本時事件觸發。

1、select()方法

下面的代碼是只要文字框獲得焦點,就會選擇全部的文本:

var textBox = document.getElementById("myForm").elements["firstName"];//設定預設值textBox.value = "input your firstName";//設定事件textBox.addEventListener("focus", function () {  event.target.select();});

2、select事件

何時觸發該事件:

  • 一般情況下只有使用者選擇了文本(而且要釋放滑鼠),才會觸發select事件;
  • IE8及更早版本中,只要使用者選擇了一個字母(不必釋放滑鼠),就會觸發select事件;
  • 在調用select()方法時也會觸發;

如:

var textBox = document.getElementById("myForm").elements["firstName"];//設定預設值textBox.value = "input your firstName";//設定事件textBox.addEventListener("select", function () {  console.log("selected");});

3、取得選擇的文本

利用兩個屬性:

  • selectionStart
  • selectionEnd

這兩個屬性儲存的是基於0的數值,表示所選擇文本的範圍(位移量)。因此要取得使用者選擇的文字框中的文本,可以使用如下代碼:

var textBox = document.getElementById("myForm").elements["firstName"];//設定預設值textBox.value = "input your firstName";//設定事件textBox.addEventListener("select", function () {  var selected = textBox.value.substring(textBox.selectionStart,textBox.selectionEnd);  console.log(selected); });

另外,也可以用該屬性來設定當獲得焦點的時候預設全選的狀態:

textBox.addEventListener("focus", function () {  textBox.selectionStart = "0";  textBox.selectionEnd = textBox.value.length;});

或者:

textBox.addEventListener("focus", function () {  textBox.blur();});

但是,使用selectionStart/End屬性時,IE8不支援,但支援另一個名為

  • document.selection對象,該對象儲存著使用者在整個文檔範圍內選擇的文本資訊

擷取選擇的文本的相容版本為:

function getSelectedText (textbox) {  if (typeof textbox.selectionStart == "number") {    return textbox.value.substring(textbox.selectionStart,textbox.selectionEnd);  }else if (document.selection) {    return document.selection.createRange().text;  }}

二、選擇部分文本

選擇部分文本的方法是:

setSelectionRange()方法。接收兩個參數:要選擇第一個字元的索引和最後一個字元的索引。
如阻止使用者選擇:

textBox.addEventListener("focus", function () {  textBox.setSelectionRange(0,0);});textBox.addEventListener("select", function () {  textBox.setSelectionRange(0,0);});

要調用setSelectionRange()之前或之後立即將焦點設定到文字框。而IE中使用的方式是適用範圍來解決文本的問題:

var range = textBox.createTextRange();range.collapse(true); //範圍摺疊到開頭range.moveStart("Character",0);range.moveEnd("Character",textBox.value.length);range.select();

相容版本:比較常用

function selectText(textbox, startIndex, stopIndex) {  if (textbox.setSelectionRange) {    textbox.setSelectionRange(startIndex, stopIndex);  } else if (textbox.createTextRange()) {    var range = textbox.createTextRange();    range.collapse(true); //範圍摺疊到開頭    range.moveStart("Character", startIndex);    range.moveEnd("Character", stopIndex);    range.select();  };}

三、過濾輸入

1、屏蔽字元

下面的代碼僅允許輸入數字:

var textBox = document.getElementById("myForm").elements["firstName"];textBox.autofocus = true;textBox.addEventListener("keypress", function () {  if (!/\d/.test(String.fromCharCode(event.charCode))) { //僅輸入數字    event.preventDefault();  };});

但是部分瀏覽器會對向上、下鍵、退格鍵觸發keypress事件,所以需要對這些常用的操作鍵取消禁止,只要不屏蔽那些字元編碼小於10的鍵即可:

textBox.addEventListener("keypress", function () {  if (!/\d/.test(String.fromCharCode(event.charCode)) && event.charCode > 9 && !event.ctrlKey) { //僅輸入數字    event.preventDefault();  };});

四、操作剪貼簿

以下是6個剪貼簿事件

  • beforecopy:在發生複製操作前觸發
  • copy:在發生複製時觸發
  • beforecut:在發生剪貼前操作
  • cut:在發生加貼時操作
  • beforepaste:在發生黏貼操作前觸發
  • paste:在發生黏貼操作時觸發

如設定禁止拷貝:

//拷貝之前提示禁止拷貝textBox.addEventListener("beforecopy", function() {  textBox.value = "do not copy";});//拷貝時禁止拷貝textBox.addEventListener("copy", function() {  event.preventDefault();});

要訪問剪貼簿中的資料,可以使用clipboardData對象,在IE中,這個對象是window對象的屬性,在friefox,safari和chrome,這個對象是相應event對象的屬性;在IE中可以隨時訪問該對象;但在其他瀏覽器中只有在處理剪貼簿事件期間才有效。

這個clipboardData對象有三個方法:

  • getData()
  • setData()
  • clearData()

getData()接收一個參數,即要取得資料的格式(IE中有兩種資料格式:text和URL;在其他瀏覽器中這個參數是一種MIME類型;不過可以用text代替text/plain)。

setData()接收兩個參數,即資料類型和要放在剪貼簿中的文本。(第一個參數中,IE支援text和URL;第二個參數中chrome和safari不支援text類型);這兩個瀏覽器在成功將文本放到剪貼簿中後,都會返回true;否則,返回false:

function getClipboardText(event) {  var clipboardData = (event.clipboardData || window.clipboardData);  return clipboardData.getData("text");}function setClipboardText(event, value) {  if (event.clipboardData) {    return event.clipboardData.setData("text/plain", value);  } else if (window.clipboardData) {    return window.clipboardData.setData("text", value);  }}

目前瀏覽器逐漸收緊對訪問剪貼簿的操作。

五、自動切換焦點

理論上就是在前一個文字框中的字元打到最大數量後,自動將焦點切換到下一個文字框:

DOM:

<form action="">  <input type="text" name="tel11" id="txtTel1" maxLength="3">  <input type="text" name="tel12" id="txtTel2" maxLength="3">  <input type="text" name="tel13" id="txtTel3" maxLength="4">  <input type="submit" name="btn" id="btn" value="submit"></form>

js:

var textbox1 = document.getElementById("txtTel1");var textbox2 = document.getElementById("txtTel2");var textbox3 = document.getElementById("txtTel3");textbox1.addEventListener("keyup", tabForward);textbox2.addEventListener("keyup", tabForward);textbox3.addEventListener("keyup", tabForward);function tabForward() {  var target = event.target;  //當value長度等於最大值的時候  if (target.value.length == target.maxLength) {    var form = target.form;    //遍曆所在的form表單中的元素    for (var i = 0, len = form.elements.length; i < len; i++) {      //如果該元素是目標元素      if (form.elements[i] == target) {        //並且該元素的下一個元素為true 其他條件        if ((form.elements[i + 1]) && (form.elements[i + 1].nodeType == 1) && (form.elements[i + 1].tagName.toLowerCase() == "input") && (form.elements[i + 1].type == "text")) {          //則下個元素獲得焦點          form.elements[i + 1].focus();        }      }    };  }}

六、HTML5約束驗證API

1、必要欄位required屬性

在必要欄位中添加屬性required。它適用於input,textarea,select欄位。使用下面的代碼可以檢測瀏覽器是否支援required屬性:

var isRequiredSupported="required" in document.createElement("input");

2、其他輸入類型

input的type屬性增加了“email”和“url”;各瀏覽器也都為它們增加了定製的驗證機制:

var input = document.createElement("input");input.type = "email";var isEmailSupported = (input.type == "email");

3、數值範圍

除了“email”和“URL”,HTML5還定義了另外幾個輸入元素。這幾個元素都要求填寫基於數位值:“number”,“range”,“datetime”,“datetime-local”,“date”,“mouth”,“week”,“time”。目前瀏覽器對這些類型支援並不好,如果真想使用的話要小心。

對這事數實值型別的輸入元素可以指定min屬性,max屬性,step屬性。同時這些數實值型別元素還有兩個方法:stepUp(),stepDown()。都接受一個參數,要在當前基礎上加上或減去的數值。

DOM:

<form action="">  <input type="range" name="tel14" id="txtTel4" required min="10" max="20" step="1">  <input type="button" value="up" id="up">  <input type="text" id="output">  <input type="submit" name="btn" id="btn" value="submit"></form>

js:

var input = document.getElementById("txtTel4");var up = document.getElementById("up");input.addEventListener("mousemove", function () {  var output = document.getElementById("output");  output.value = input.value;});up.addEventListener("click", function () {  //點擊value值以2為單位增加  input.stepUp(2);  var output = document.getElementById("output");  output.value = input.value;});

3、輸入模式

HTML5新增了pattern屬性,這個屬性的值是一個Regex,用於匹配文字框中的值。

<input type="text" id="number" pattern="\d{3}">var num = document.getElementById("number");console.log(num.pattern); //\d{3}

可以使用以下代碼來檢測瀏覽器是否支援pattern屬性:

var isPatternSupported="pattern" in document.createElement("input");

4、檢測有效性

使用checkValidity()方法可以檢測表單中的欄位是否有效。所有表單的欄位都有這個方法,如果檢查有效返回true。

<form action="">  <input type="text" pattern="w" id="name" required>  <input type="number" max="10" id="num" required>  <input type="button" id="check" value="check">  <input type="submit" id="submit" value="submit" disabled></form>var form = document.forms[0];var name = document.getElementById("name");var number = document.getElementById("num");var check = document.getElementById("check");var submit = document.getElementById("submit");check.addEventListener("click", function () {  console.log(form.checkValidity()); //檢測整個表單是否正確  if (form.checkValidity()) {    submit.removeAttribute("disabled");    check.disabled = true;  }else{    alert("請檢查表單");  }});

input的validity屬性會給出什麼欄位有效和無效的具體資訊。

var inputName = document.getElementById("inputName");inputName.onblur = function() {  if (inputName.checkValidity()) {    inputName.style.color = "white";    inputName.style.backgroundColor = "green";  } else {    inputName.style.color = "white";    inputName.style.backgroundColor = "red";    if (inputName.validity.patternMismatch) {      inputName.value = "請填寫正確的格式";    }  }};inputName.addEventListener("mouseenter", function () {  inputName.focus();  inputName.select();});

validity主要包括下列屬性:

  • customError:是否設定了setCustomValidity();
  • patternMismatch:是否與pattern屬性匹配;
  • rangeOverflow:是否比max值大;
  • rangeUnderflow:是否比min值小;
  • stepMisMatch:步長是否合理;
  • tooLong:是否超過了maxlength;
  • typeMismatch:是否不是mail類型和url類型;
  • valid:如果這裡的其他屬性都是false,返回true;
  • valueMissing:如果為required中沒有值,返回true。

5、禁用驗證

通過設定表單的novalidate屬性,可以是表單不進行驗證。用js擷取form之後,設定它的novalidate屬性為true,會禁用表單驗證。

在提交按鈕上添加formnovalidate屬性,會不驗證提交表單。用js擷取submit按鈕之後,設定它的formnovalidata屬性為true,會禁用表單驗證並提交。
以上就是本文的全部內容,希望對大家的學習有所協助。

您可能感興趣的文章:
  • javascript之文字框輸入四個數字自動加空格的指令碼
  • js添加刪除行和雙擊變文字框的指令碼
  • 改變文字框字型顏色的js指令碼
  • js限制文字框輸入長度兩種限制方式(長度、位元組數)
  • JS文字框不能輸入空格驗證方法
  • JS控制文字框textarea輸入字數限制的方法
  • 滑鼠焦點離開文字框時驗證的js代碼
  • js擷取游標位置和設定文字框游標位置範例程式碼
  • JS判斷文字框內容改變事件的簡單一實例
  • js限制文字框只能輸入數字方法小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.