HTML【详解】超链接 a 标签的四大功能(页面跳转、页内滚动【锚点】、页面刷新、文件下载)

超链接 a 标签主要有以下功能:

跳转到其他页面

 <a href="https://www.baidu.com/" target="_blank" >百度</a>
  • href:目标页面的 url 地址或同网站的其他页面地址,如 detail.html
  • target:打开目标页面的方式
    • _self:在同一个网页中显示(默认值)
    • _blank:在新的窗口中打开【常用】
    • _parent:在父窗口中显示
    • _top:在顶级窗口中显示

锚点 – 页内滚动

回到页面顶部

<a href="#">回到顶部</a>

滚动到指定元素

<a href="#title2">页内滚动到标题2</a>
  • href:# + 指定元素的 id 或 name

在这里插入图片描述

<template>
  <div class="page">
    <h1>标题1</h1>
    <p>段落1</p>
    <p>段落2</p>

    <h1 id="title2">标题2</h1>

    <div class="menuBox">
      <a href="#title2">页内滚动到标题2</a>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page {
  height: 2000px;
}
.menuBox {
  position: fixed;
  right: 20px;
  bottom: 20px;
}
</style>

跳转到其他页面并滚动到指定元素

<a href="index.html#menu">打开首页,并滚动到菜单</a>

刷新页面

<a href="">刷新页面</a>
  • href 为空

下载文件

<a href="/user/test/xxxx.txt" download="文件名.txt">点击下载</a>
  • href:目标文件的 url 地址
  • download:指定下载后文件的名称,若无,则使用默认文件名
txt、png、jpg 等浏览器支持直接打开的文件必须添加 download 属性,否则不会执行下载任务,而会直接打开文件。

访问接口,返回文件流进行下载时,也会用到 !

// 根据接口返回的文件流数据 data, 创建 blob 对象
const blob = new Blob([data], { type: headers['content-type'] })
// 生成指向 blob 对象的临时 URL
const downUrl = window.URL.createObjectURL(blob)
// 创建 a 链接
const dom_a = document.createElement('a')
// a 链接的 href 属性为 blob 对象的临时 URL
dom_a.href = downUrl
// a 链接的 download 属性为进行URL解码的 fileName
dom_a.download = decodeURIComponent(fileName)
// a 链接的 display 样式为 none,避免在页面上显示
dom_a.style.display = 'none'
// 将 a 链接添加到 body 标签中
document.body.appendChild(dom_a)
// 点击 a 链接,触发文件的下载
dom_a.click()
// 将 a 链接从父标签(此处为 body )中移除
dom_a.parentNode.removeChild(dom_a)
// 清除指向 blob 对象的临时 URL
window.URL.revokeObjectURL(url)

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 23:16:07       50 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 23:16:07       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 23:16:07       43 阅读
  4. Python语言-面向对象

    2024-07-09 23:16:07       54 阅读

热门阅读

  1. Linux C++ 046-设计模式之策略模式

    2024-07-09 23:16:07       23 阅读
  2. 2024年二级建造师考试题库及答案

    2024-07-09 23:16:07       23 阅读
  3. 深入解析Spring Boot的application.yml配置文件

    2024-07-09 23:16:07       23 阅读
  4. Docker技术简介

    2024-07-09 23:16:07       19 阅读
  5. Qt 的 qmake的语法简介与例子介绍

    2024-07-09 23:16:07       22 阅读
  6. C#用链表和数组分别实现堆栈

    2024-07-09 23:16:07       21 阅读
  7. Go bytes包

    2024-07-09 23:16:07       24 阅读