HTML常用标签

175 阅读3分钟

1. <a> 元素

1.1 属性

(1)href:超链接

href 取值的类型

  • 网址:如 https://google.comhttp://google.com//google.com(最高级,会自动选择适用 http 还是 https)
  • 路径:/a/b/c、/index.html、./index.html
  • 伪协议:javascript:代码;、mailto:邮箱、tel:手机号
  • id:href="#aaa"

备注:

  • 如果开启了 http 服务,那么 "/" 不是硬盘的根目录,此时开启服务的位置是根目录。
  • javascript:; 用于点击 a 标签但什么都不做的场景,避免点击页面刷新。

(2)target:目标窗口

target 取值

  • _blank 新页面打开
  • _self 默认值,当前页打开
  • _parent 父级窗口打开
  • _top 最顶层窗口打开

备注:

  • target="aaa",如果有name 为 aaa 的窗口就使用它,没有就创建一个新窗口,并将它称为 aaa。其他链接 target="aaa" 时也会在该窗口打开。还可设置 iframe 标签的 name 属性为 aaa,可同时引入多个网页。

(3)download:下载网页(但大多暂不支持)

(4)rel = noopener

当打开不受信任的链接时,确保它们无法通过Window.opener属性来篡改原页面内容

<a href="https:www.google.com" target="_blank" rel="noopener"></a>

1.2 作用

  • 跳转到外部页面
  • 跳转到内部锚点
  • 跳转到邮箱或电话

2. <table> 元素

2.1 相关标签

  • thead
  • tbody
  • tfoot

以上三个标签结构必须写,否则会默认都放到 tbody 里

  • th:表头
  • tr:行
  • td:数据

2.2 相关样式

  • table-layout:默认为 auto,自动计算单元格的宽度。fixed,按设置的总宽度平均分配。
  • border-collapse:collapse 合并表格,去除间隙
  • border-spacing:表格间的空隙

3. <img> 元素

  • 作用:发出 get 请求,展示图片。
  • 属性: alt / width / height / src
  • 事件:onload / onerror

监听图片是否加载成功,可用于在图片加载失败后进行挽救,优化用户体验

aaa.onload = function() {
    console.log('加载成功')
}
aaa.onerror = function() {
    aaa.src = '/404.png'
}
  • 响应式
img {
    max-width: 100%;
}
  • 典型的可替换元素:iframe / video / embed / img

4. <form> 元素

  • 作用:发 get 或 post 请求,然后刷新页面
  • 属性:method、action、autocomplete、target

(1)method="GET"、method="POST"
(2)action,请求前往的页面
(3)autocomplete = on/off,自动填充。当 input 输入框 name="username"等值时,输入时输入框会给出相应提示。
(4)target="aaa",将 aaa 作为目标窗口

  • 事件:onsubmit

用户提交表单时触发该事件

  • 备注

form 里的 input 都应该有 name 属性。form 必须有一个 type="submit" 的按钮,表单才能提交。

5. <input> 元素

5.1 属性

  • 类型:text / color / password / radio / checkbok / file / hidden / number / search / tel / email

(1) file 多选文件时,添加 multiple
(2) hidden 隐藏的 input,用于 js 自动填写数据提交,如用户 id

  • 其他:name / autofocus / checked / disabled / maxlength / pattern / value / placehoulder

pattern 检查 value 的正则表达式必须匹配整个值,否则通过 title 属性设置给出提示信息

<!-- 只能包含三个字母的文本字段 -->
<input type="text" pattern="[A-z]{3}"> 

5.2 事件

  • onchange:当用户输入改变时触发
  • onfocus:鼠标聚焦时触发
  • onblur:鼠标失去焦点时触发

5.3 验证器(HTML5 新功能)

  • required:有此属性时,字段必须填写,否则会给出提示。不填写无法提交。

5.4 其他

  • <input type="submit"> 和 <button type="submit"></button> 的区别是什么?

唯一区别:button 里还可以有其他标签元素,如<strong>、<img>等

  • 一般不监听 input 的 click 事件,而是关注 onfocus

6. <textarea> 元素

设置禁止拖拽

<textarea style="resize:none;"></textarea>