一些你可能不知道但非常有用的 HTML 标签
1. Details + Summary
detail 与 summary 标签组合使用,就能实现折叠面板(Collapse)的效果:
<details>
<summary>Details👈</summary>
Something small enough to escape casual notice.
</details>
2.Fieldset + Legend
元素用于对表单中的控制元素进行分组(也包括 label 元素),如果其中有 元素,会放在块级框起始处的边界上:<fieldset>
<legend>Choose your favorite monster</legend>
<input type="radio" id="kraken" name="monster">
<label for="kraken">Kraken</label><br/>
<input type="radio" id="sasquatch" name="monster">
<label for="sasquatch">Sasquatch</label><br/>
<input type="radio" id="mothman" name="monster">
<label for="mothman">Mothman</label>
</fieldset>
3. Meter
元素用来显示已知范围的标量值或者分数值。简单来说,使用该元素,就能实现计量器的效果:
Heat the oven to <meter min="200" max="500" value="350">350 degrees</meter>
指定min和max属性就能确定区间,如果value不在区间内,value就会取最接近的一端的值。此外它也能和表单关联、设定上下限值等,更多用法请看 MDN
4. Progress
从其名字上就知道元素就是作为进度条展示。在不指定 value 的情况下,它将来回播放展示:
<progress></progress>
同样的,也可以为其指定 value 和最大值(max):
<progress value="70" max="100">70 %</progress>
可以看到,在展示上和 meter 标签相似,对于简单的展示任务进度场景,使用它完全没问题。
5. Datalist
可以包含一组 元素,用于表示其它表单控件可选值。例如普通的文本输入框是没有可选输入值的,但借助 datalist 可以做到:
<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
只需要为 input 标签指定 list 属性,其值为 datalist 元素的 id 就可以将二者关联起来。并且它本身就具备了模糊搜索🔍功能。如果在 option 标签内添加文本,也会展示在 datalist 中作为选项的描述信息:
6. OptGroup
有时候需要为 元素中的选项创建分组,这时 就派上用场了:
<label for="dino-select">Choose a dinosaur:</label>
<select id="dino-select">
<optgroup label="Theropods">
<option>Tyrannosaurus</option>
<option>Velociraptor</option>
<option>Deinonychus</option>
</optgroup>
<optgroup label="Sauropods">
<option>Diplodocus</option>
<option>Saltasaurus</option>
<option>Apatosaurus</option>
</optgroup>
</select>
下面是在 Firefox 浏览器上的效果:
7. Input 系列
通过指定 的 type 属性可以得到不同的表单控件,这里只介绍两种不常见但是非常有用的——
2.1 ColorPicker
指定 type 为 color,就能创建一个颜色选择器(ColorPicker):
<input type="color">
据 MDN 介绍,此元素的外观会因浏览器不同而不同,可能是简单的验证颜色输入格式的文本框,也可能使用平台原生或自定义样式的颜色选择器。在 93 版本 Chrome(Mac)上呈现的效果如下:
它甚至内置了屏幕取色器功能。有兴趣的小伙伴可以在不同平台、浏览器上看下,还是相当惊艳的。通过指定 value 属性可以指定默认颜色值,不指定的情况下默认是 #000000(全黑)。
2.2 Slider
当 type 为 range 时,就可以实现一个滑动输入条(Slider):
<p>Audio settings:</p>
<div>
<input type="range" id="volume" name="volume"
min="0" max="11">
<label for="volume">Volume</label>
</div>
<div>
<input type="range" id="cowbell" name="cowbell"
min="0" max="100" value="90" step="10">
<label for="cowbell">Cowbell</label>
</div>