前端常见需求整理 - 全局相关(修改页面标题、复制文本、点击下载图片)

H5修改页面标题

// 修改页面标题
export const changeDocumentTitle = (name: string) => {
  // 设置初始化的时候页面的标题,兼容 ios 的情况
  let i = document.createElement("iframe");
  i.src = "https://xxx.com/favicon.ico";
  i.style.display = "none";
  i.onload = function () {
    setTimeout(function () {
      i.remove();
    }, 9);
  };
  document.title = name;
  document.body.appendChild(i);
};

需要获取一个较小的资源来辅助实现。

其它实现

export const setDocumentTitle = function (title) {
  document.title = title
  const ua = navigator.userAgent
  // eslint-disable-next-line
  const regex = /\bMicroMessenger\/([\d\.]+)/
  if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
    const i = document.createElement('iframe')
    i.src = '/favicon.ico'
    i.style.display = 'none'
    i.onload = function () {
      setTimeout(function () {
        i.remove()
      }, 9)
    }
    document.body.appendChild(i)
  }
}

复制文本

function copy(text) {
  const url = text;
  // 新建一个文本框
  const oInput = document.createElement('input');
  // 赋值给文本框
  oInput.value = url;
  document.body.appendChild(oInput);
  // 选择对象;
  oInput.select();
  // 执行浏览器复制命令
  document.execCommand('Copy');
  // 复制完成删除掉输入框
  document.body.removeChild(oInput);
  // 复制成功提醒
},

web点击下载图片

点击链接元素下载图片

<a-button type="primary">
  <a download="qrcode.png" @click='download' id="download">下载</a>
</a-button>

<script>
const download = function () {
  let canvas = document.getElementsByTagName('canvas')[0]
  document.getElementById('download').setAttribute('href', canvas.toDataURL())
}
</script>

点击非链接元素下载图片

handleOks() {
  let src = this.$refs["qrcodeImage"].dataUrl;
  let a = document.createElement("a");
  a.href = src;
  a.download = "qrcode.png";
  a.click();
}

补充的话

仓库,还提供了许多前端常见需求及实现的归纳整理,欢迎客官看看~

如果这篇笔记能够帮助到你,请帮忙在 github 上点亮 star,感谢!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值