跳至主要內容

JavaScript 文本选中检测

h7ml大约 2 分钟

JavaScript 文本选中检测

选中文本

inp.select(); // 选中文本框中的所有文字
function getSelectedText(text){
if(typeof text.selectionStart == 'number'){// 选择文字的起始,结束下标
  return text.value.substring(text.selectionStart,text.selectionEnd);
}else if(document.selecttion){// IE 取得 IE 中的选择文本代码 调用 document.selecttion 不需要考虑 text 参数
  return document.selecttion.createRang().text;}
}

输入检测

检测浏览器是否支持 pattern 属性

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

input.stepUp(); // 加 1
input.stepUp(5); // 加 5
input.stepDown(); // 减 1
input.stepDown(5); // 减 5

// 检测有效性
if (document.forms[0].checkValidity()) {
  // 整个表单有效,返回 true。 也可以单独 input 调用这个方法
}
  • customError:如果设置了 setCustomValidity(),则为 true,否则返回 false
  • patternMismatch:如果值与指定的 pattern 属性不匹配,返回 true
  • reangeOverflow:如果值比 max 值大,返回 true
  • rangeUnderflow:如果值比 min 值小,返回 true
  • stepMisMatch:如果 min 和 max 直接的步长值不合理,返回 true
  • tooLong:值的长度超过了 maxlenght 属性指定的长度,返回 true。火狐会自动约束字符数量,所以会永远返回 true
  • typeMismatch:如果值不是 'mail' 或 'url' 要求的格式,返回 true
  • valid:如果这里的属性都是 false,返回 true。checkValidity() 也要求相同的值
  • valueMissing:如果标注为 required 的字段中没有值,返回 true

选择框脚本

  • add(new option, relOption):向控件中插入行的 <option>
  • multiple:布尔值,是否允许多选
  • options:控件中所有 <option> 元素的 HTMLCollection
  • remove(index):移除给定位置的选项
  • selectedIndex:选中的索引,从 0 开始,没有则是 -1
  • size:选择框可见的行数

每个 <option> 都有一个 HTMLOptionElement 对象

  • index:当前选项在 option 集合中的索引
  • label:当前选择的标签;等价于 html 中 label 的特性
  • selected:布尔值,表示当前选项是否被选中,设为 true 可以选中当前选项
  • text:选项的文本
  • value:选项的值