默认情况下,<input>
或 <textarea>
元素中的占位符文本颜色是半透明或浅灰色。
::placeholder 伪元素是输入的 placeholder 文本,可以通过它给占位文本设置 CSS 样式。
<style>
input {
padding: 2px 4px;
}
input::placeholder {
color: red;
font-size: 1.2em;
font-style: italic;
}
</style>
<input placeholder="在此输入" />
上面代码的运行效果如下:
使用 CSS 属性 caret-color 用来定义<input>
或 <textarea>
元素获得焦点时插入光标的颜色。
<style>
input {
caret-color: red;
font:
16px "Helvetica",
"Arial",
"sans-serif";
}
</style>
<label for="textInput">请注意红色光标:</label>
<input id="textInput" size="32" />
上面代码的运行效果如下:
search 类型的 <input>
元素与 text 类型的元素非常相似,不同之处在于它们专门用于处理搜索效果。具体体现就是输入内容后 <input>
元素的末尾会显示一个删除元素,且点击该删除元素能清空 <input>
的内容。
<form>
<div>
<input type="search" id="mySearch" name="q" placeholder="站内搜索..." />
<button>搜索</button>
</div>
</form>
上面代码的运行效果如下:
把input元素的type属性设置为color,无需第三方插件将会展示为颜色选择控件:
<input type="color" />
上面代码的运行效果如下:
当把input元素的type属性设置为以下几个值时,无需第三方插件将会展示为相应类型的日期时间选择控件:
<input type="date" />
<input type="datetime-local" />
<input type="time" />
<input type="month" />
<input type="week" />
<input>
基于HTMLInputElement接口,该接口提供了一些管理<input>
的方法。
<textarea>
元素或者type=text的 <input>
元素里的所有内容。<input type="text" id="text-box" size="20" value="Hello world!" />
<button onclick="selectText()">选择文本</button>
<script>
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.select();
}
</script>
运行上面的代码,点击选择文本按钮的效果如下:
<input>
或 <textarea>
元素中当前选中文本的起始和结束位置。<input type="text" id="text-box" size="20" value="Mozilla" />
<button onclick="selectText()">选择文本</button>
<script>
function selectText() {
const input = document.getElementById("text-box");
input.focus();
input.setSelectionRange(0, 5);
}
</script>
运行上面的代码,点击选择文本按钮的效果如下:
⚠️ 注意:
<input>
或<textarea>
元素必须先获得焦点才能产生选中效果。
给select元素设置css属性appearance: none,将会隐藏select的小箭头,便于我们美化select元素的UI展示。
<select style='appearance: none; padding: 2px 6px;'>
<option>请选择...</option>
</select>
移除select小箭头的效果如下:
先看效果:
实现代码:
<style>
hr {
border: none;
border-top: 3px dotted #999;
color: #333;
overflow: visible;
text-align: center;
height: 5px;
}
hr::after {
background: #fff;
content: "👇🏻👇🏻👇🏻👇🏻";
padding: 0 4px;
position: relative;
top: -13px;
}
</style>
<hr />