在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.

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版
中文版,非常好用

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),