zoukankan      html  css  js  c++  java
  • js一键复制文本

    一、需求分析 

           开发过程中会遇到一键复制的需求,解决的方法很简单,我们只需要在页面中添加一个 textarea标签,通过textarea的select方法选中文本,然后再通过浏览器提供的copy 命令,将textarea中的内容复制下来即可。

      注:浏览器提供的copy 命令:document.execCommand("copy")

        textarea的select方法:textarea.select()

    二、代码实现

    import React from 'react';
    import { Button } from 'antd'
    export default () => {
      const copyString = () => {
       //可以直接复制字符串 // let content = `我寻你千百度 日出到迟暮 一瓢江湖我沉浮 我寻你千百度 又一岁荣枯 可你从不在 灯火阑珊处 ` let content = document.getElementById('preId') ?.innerText; if (content) { const el = document.createElement('textarea'); //创建一个textarea el.value = content; //textarea的内容 el.setAttribute('readonly', ''); //添加相应的属性,不影响整体布局 el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); //textarea添加到body el.select(); //select() 方法只对
    <input> 和 <textarea> 有效 document.execCommand('copy'); //拷贝当前选中内容到剪贴板 document.body.removeChild(el); //移除textarea }; } return ( <div> <pre id='preId'>{`我寻你千百度 日出到迟暮 一瓢江湖我沉浮 我寻你千百度 又一岁荣枯 可你从不在 灯火阑珊处 `} </pre> <Button onClick={copyString}>一键复制</Button> </div> ); }
  • 相关阅读:
    BGP的属性与配置
    IS-IS协议的简单设置
    ospf中建立虚链路、ospf与rip的重分发 stup与nssa区域的建立
    静态路由 默认路由 浮动路由配置
    centos7防火墙机制iptables与ebtables差别
    centos7虚拟机qemu学习
    centos7安装vncserver(windows控制其图形化界面)
    centos7虚拟机扩容
    centos7安装graylog
    centos7修改网卡
  • 原文地址:https://www.cnblogs.com/minorf/p/13030832.html
Copyright © 2011-2022 走看看