标梵互动教你js怎么点击复制链接并且选中文本?
To love is to enter into the inevitability of one day not being able to protect what is most valuable to you.
——Mohsin Hamid, Exit West
主要是要创建一个range,注释写的很清楚
import React, { useState } from 'react'
import { Input, message } from 'antd';
import './index.scss'
export default ({ userInfomation = {}, type, isVisible, handleToggleLayer, jobName = '' }) => {
const [tabType, setTabType] = useState(1)
const tenantId = localStorage.getItem('tenantId')
const [inputValue, setInputValue] = useState(`${window.location.href}`)
const onChangeInput = e => {
// console.log(e.currentTarget.value);
const v = e.currentTarget.value
setInputValue(v)
};
//复制功能
const copylink = () => {
// 在选择节点的时候,一定要只选择input
const copyDOM = document.querySelector('.middel-layer input'); //需要复制文字的节点
const range = document.createRange(); //创建一个range
window.getSelection().removeAllRanges(); //清除页面中已有的selection
range.selectNode(copyDOM); // 选中需要复制的节点
window.getSelection().addRange(range); // 执行选中元素
const successful = document.execCommand('copy'); // 执行 copy 操作
if (successful) {
// copyDOM.select();
message.success('复制成功!')
} else {
message.warning('复制失败,请手动复制!')
}
// 移除选中的元素
window.getSelection().removeAllRanges();
}
const onSelectInput = () => {
copyAccessKey()
document.querySelector('.middel-layer input').select() // 选中
}
return <div className={`layer-container ${isVisible ? '' : 'isHidden'}`}>
{
type === 7 ?
<div className='layer-content time-layer'>
<div className='time-layer-top border-bo'>
<div className='top-left'>
<div className='top-item active-txt' onClick={() => setTabType(1)}>
<span>链接分享</span>
<i />
</div>
</div>
<div className='close-time-img iconfont iconpopup-close-bt' onClick={() => handleToggleLayer(false)} />
</div>
<div className='share-item'>
<div className='middel-layer'>
<h4>分享职位:{jobName}</h4>
<Input
placeholder='链接'
allowClear={false}
onChange={e => onChangeInput(e)}
prefix='链接'
value={inputValue}
onFocus={() => onSelectInput()}
// defaultValue={inputValue}
/>
<p>可以将链接发送给你的微信、QQ等好友</p>
</div>
<div className='share-bottom-btn'>
<span className='cancle-btn' onClick={() => handleToggleLayer(false)}>取消</span>
<span onClick={() => copylink()}>复制链接</span>
</div>
</div>
</div> : ''
}
</div>
}
);
};
看一下效果图吧
爱一个人,就不可避免地要面对有一天会失去心之所爱的风险。—— Mohsin Hamid, Exit West
文章来源:Biaofun标梵互动(https://www.biaofun.com/)