ホームページ > ウェブフロントエンド > jsチュートリアル > JavaScript テキスト ボックスを記述する際の注意事項 scripts_javascript のヒント

JavaScript テキスト ボックスを記述する際の注意事項 scripts_javascript のヒント

WBOY
リリース: 2016-05-16 15:18:32
オリジナル
1391 人が閲覧しました

In HTML, there are two ways to represent text boxes:

One is a single line of text using input elements, and the other is a multi-line text box using textarea.

To use the input method, type must be added and set to "text".

    The
  • size property allows you to specify the number of characters that can be displayed in the text box.
  • The
  • value attribute can set the initial value of the text box.
  • The
  • maxlength attribute is used to specify the maximum number of characters that can be accepted in the text box.

The initial value of textarea must be placed within the start and end tags.

  • cols is the number of text box character lines;
  • rows is the number of text box character columns;

In addition, you cannot specify the maximum number of characters for textarea in HTML;

1. Select text

Both of the above text boxes are supported

  • select() method, this method is mainly used to select all text in the text box. Does not accept any parameters.
  • The select event corresponding to this method is triggered when the text in the text box is selected.

1. select() method

The following code will select all text as long as the text box gets focus:

var textBox = document.getElementById("myForm").elements["firstName"];
//设置默认值
textBox.value = "input your firstName";
//设置事件
textBox.addEventListener("focus", function () {
  event.target.select();
});
ログイン後にコピー

2. select event

When this event is triggered:

  • Generally, the select event will be triggered only when the user selects text (and releases the mouse);
  • In IE8 and earlier versions, as long as the user selects a letter (without releasing the mouse), the select event will be triggered;
  • will also be triggered when the select() method is called;

For example:

var textBox = document.getElementById("myForm").elements["firstName"];
//设置默认值
textBox.value = "input your firstName";
//设置事件
textBox.addEventListener("select", function () {
  console.log("selected");
});
ログイン後にコピー

3. Get the selected text

Use of two attributes:

  • selectionStart
  • selectionEnd

These two attributes store 0-based values, indicating the range (offset) of the selected text. Therefore, to get the text in the text box selected by the user, you can use the following code:

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); 
});
ログイン後にコピー

In addition, you can also use this attribute to set the default all-selected state when focus is obtained:

textBox.addEventListener("focus", function () {
  textBox.selectionStart = "0";
  textBox.selectionEnd = textBox.value.length;
});
ログイン後にコピー

or:

textBox.addEventListener("focus", function () {
  textBox.blur();
});
ログイン後にコピー

However, when using the selectionStart/End attributes, IE8 does not support it, but supports another one named

  • document.selection object, which stores the text information selected by the user within the entire document

Get the compatible version of the selected text:

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;
  }
}
ログイン後にコピー

2. Select part of the text

The method to select part of the text is:

setSelectionRange() method . Receives two parameters: the index of the first character to be selected and the index of the last character.
To block user selection:

textBox.addEventListener("focus", function () {
  textBox.setSelectionRange(0,0);
});
textBox.addEventListener("select", function () {
  textBox.setSelectionRange(0,0);
});
ログイン後にコピー

To set focus to the text box immediately before or after calling setSelectionRange(). The method used in IE is the scope of application to solve text problems:

var range = textBox.createTextRange();
range.collapse(true); //范围折叠到开头
range.moveStart("Character",0);
range.moveEnd("Character",textBox.value.length);
range.select();
ログイン後にコピー

Compatible version: more commonly used

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();
  };
}
ログイン後にコピー

3. Filter input

1. Block characters

The following code only allows entering numbers:

var textBox = document.getElementById("myForm").elements["firstName"];
textBox.autofocus = true;
textBox.addEventListener("keypress", function () {
  if (!/\d/.test(String.fromCharCode(event.charCode))) { //仅输入数字
    event.preventDefault();
  };
});
ログイン後にコピー

However, some browsers will trigger keypress events for the up, down, and backspace keys, so you need to unban these commonly used operation keys, as long as you do not block those keys whose character encoding is less than 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主要包括下列屬性:

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

5、停用驗證

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

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

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート