[转载][html]3个input元素的不常用属性
1、defaultValue
HTML
<input type="text" value="Hello world">
JavaScript
const input = document.querySelector('input');
console.log(input.value); // 'Hello world'
input.value = 'New value';
console.log(input.value); // 'New value'
console.log(input.defaultValue); // 'Hello world'
如代码所示,当用JavaScript改变了input的value后,可以使用defaultValue来获取这个元素的初始值。
2、indeterminate
大家一定都知道,Windows自带的chcekbox是有三种状态的:未选中、部分选中、选中。实际上HTML元素中的chcekbox也可以显示这三种状态:
HTML
<input type="checkbox" />JavaScript
const input = document.querySelector('input');
input.indeterminate = true;效果如下图:
不同的操作系统、不同的浏览器,显示的效果可能不同。
需要注意的是,这个属性仅仅是在视觉上起作用,实际提交到服务器的checkbox值还是checked或者unchecked。
3、selectionStart, selectionEnd 和 selectionDirection
HTML
<input type="text" />JavaScript
const input = document.querySelector('input');
setInterval( _ => {
console.log(
input.selectionStart,
input.selectionEnd,
input.selectionDirection;
); // e.g. 2, 5, "forward"
}, 1000)当选中文本框的文字时,控制台就会出现所选文字的起始位置、结束位置、选择方向。
转载自https://dev.to/stefanjudis/three-input-element-properties-that-i-discovered-while-reading-mdn-30fg