首頁 web前端 js教程 JavaScript文字方塊腳本所寫的注意事項_javascript技巧

JavaScript文字方塊腳本所寫的注意事項_javascript技巧

May 16, 2016 pm 03:18 PM
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属性,这个属性的值是一个正则表达式,用于匹配文本框中的值。

<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 mainly includes the following attributes:

  • customError: whether setCustomValidity() is set;
  • patternMismatch: whether it matches the pattern attribute;
  • rangeOverflow: whether it is larger than the max value;
  • rangeUnderflow: whether it is smaller than the min value;
  • stepMisMatch: whether the step size is reasonable;
  • tooLong: whether maxlength is exceeded;
  • typeMismatch: whether it is not the mail type and url type;
  • valid: If other attributes here are false, return true;
  • valueMissing: If there is no value in required, return true.

5. Disable verification

By setting the novalidate attribute of the form, the form can not be verified. After obtaining the form using js, setting its novalidate attribute to true will disable form validation.

Adding the formnovalidate attribute to the submit button will not validate the submitted form. After using js to get the submit button, set its formnovalidata attribute to true, which will disable form validation and submit it.
The above is the entire content of this article, I hope it will be helpful to everyone's study.

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何在Linux系統中執行.sh檔? 如何在Linux系統中執行.sh檔? Mar 14, 2024 pm 06:42 PM

如何在Linux系統中執行.sh檔?在Linux系統中,.sh文件是一種被稱為Shell腳本的文件,用於執行一系列的命令。執行.sh檔案是非常常見的操作,本文將介紹如何在Linux系統中執行.sh文件,並提供具體的程式碼範例。方法一:使用絕對路徑執行.sh文件要在Linux系統中執行一個.sh文件,可以使用絕對路徑來指定該文件的位置。以下是具體的步驟:打開終

剪映怎麼製作腳本?剪下製作腳本的方法教程 剪映怎麼製作腳本?剪下製作腳本的方法教程 Mar 13, 2024 pm 12:46 PM

  剪映是影片編輯工具,具有全面的剪輯功能,支援變速,有多元濾鏡和美顏的效果,還有豐富的曲庫資源。在這款軟體中,可以直接對影片進行剪輯,也可以建立剪輯腳本,但是該怎麼操作呢?本篇教學小編就來介紹一下剪映製作腳本的方法。  製作方法  1、在電腦中點選開啟剪映軟體,然後找到「創作腳本」選項,點選開啟。  2、在創作腳本頁面中,輸入“腳本標題”,然後在大綱中輸入拍攝內容的簡介。  3、如何在大綱中就能看到「分鏡描述」選項,在框內可以

如何使用WebSocket和JavaScript實現線上語音辨識系統 如何使用WebSocket和JavaScript實現線上語音辨識系統 Dec 17, 2023 pm 02:54 PM

如何使用WebSocket和JavaScript實現線上語音辨識系統引言:隨著科技的不斷發展,語音辨識技術已成為了人工智慧領域的重要組成部分。而基於WebSocket和JavaScript實現的線上語音辨識系統,具備了低延遲、即時性和跨平台的特點,成為了廣泛應用的解決方案。本文將介紹如何使用WebSocket和JavaScript來實現線上語音辨識系

WebSocket與JavaScript:實現即時監控系統的關鍵技術 WebSocket與JavaScript:實現即時監控系統的關鍵技術 Dec 17, 2023 pm 05:30 PM

WebSocket與JavaScript:實現即時監控系統的關鍵技術引言:隨著互聯網技術的快速發展,即時監控系統在各個領域中得到了廣泛的應用。而實現即時監控的關鍵技術之一就是WebSocket與JavaScript的結合使用。本文將介紹WebSocket與JavaScript在即時監控系統中的應用,並給出程式碼範例,詳細解釋其實作原理。一、WebSocket技

如何利用JavaScript和WebSocket實現即時線上點餐系統 如何利用JavaScript和WebSocket實現即時線上點餐系統 Dec 17, 2023 pm 12:09 PM

如何利用JavaScript和WebSocket實現即時線上點餐系統介紹:隨著網路的普及和技術的進步,越來越多的餐廳開始提供線上點餐服務。為了實現即時線上點餐系統,我們可以利用JavaScript和WebSocket技術。 WebSocket是一種基於TCP協定的全雙工通訊協議,可實現客戶端與伺服器的即時雙向通訊。在即時線上點餐系統中,當使用者選擇菜餚並下訂單

初學者的Windows PowerShell腳本教學 初學者的Windows PowerShell腳本教學 Mar 13, 2024 pm 10:55 PM

我們為初學者設計了這份WindowsPowerShell腳本教程,無論您是技術愛好者還是希望提高腳本編寫技能的專業人士。如果你對PowerShell腳本沒有先驗知識,這篇文章將從基礎開始,為您量身訂做。我們將協助您掌握PowerShell環境的安裝步驟,並逐步介紹PowerShell腳本的主要概念和功能。如果您已經做好準備,準備深入學習PowerShell腳本編程,那麼讓我們一起踏上這趟令人興奮的學習之旅吧!什麼是WindowsPowerShell? PowerShell是由微軟開發的混合了命令

如何使用WebSocket和JavaScript實現線上預約系統 如何使用WebSocket和JavaScript實現線上預約系統 Dec 17, 2023 am 09:39 AM

如何使用WebSocket和JavaScript實現線上預約系統在當今數位化的時代,越來越多的業務和服務都需要提供線上預約功能。而實現一個高效、即時的線上預約系統是至關重要的。本文將介紹如何使用WebSocket和JavaScript來實作一個線上預約系統,並提供具體的程式碼範例。一、什麼是WebSocketWebSocket是一種在單一TCP連線上進行全雙工

JavaScript與WebSocket:打造高效率的即時天氣預報系統 JavaScript與WebSocket:打造高效率的即時天氣預報系統 Dec 17, 2023 pm 05:13 PM

JavaScript和WebSocket:打造高效的即時天氣預報系統引言:如今,天氣預報的準確性對於日常生活以及決策制定具有重要意義。隨著技術的發展,我們可以透過即時獲取天氣數據來提供更準確可靠的天氣預報。在本文中,我們將學習如何使用JavaScript和WebSocket技術,來建立一個高效的即時天氣預報系統。本文將透過具體的程式碼範例來展示實現的過程。 We

See all articles