以前因为公司的业务需求,须要点击实现微信号复制功能。今天说下js里面document.execCommand()方法实现复制功能。css
本次案例实现涉及如下几点:html
1.点击打开弹窗关闭弹窗的功能;display:block和display:none的切换html5
2.H5提供的API-range对象;具体可去《HTML5编辑API之Range对象》查看.
浏览器
3.document.execCommand()方法使用。具体用法地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand微信
HTML部分post
<button onClick='_toolTipOpen()'>打开弹窗</button> <!-- 弹窗内容 --> <div id='_toolTipBox' onClick='_toolTipClose()'></div> <div id='_toolTip'> <div class='_tipText'>加[李四]微信好友</div> <div class='_tipCode '><span id="wechatCode">wechat</span></div> <div class='_tipCopy ' onclick="copywx()">点击复制</div> <a class='_tipOpenAPP' href='weixin://'>打开微信<span>(如无反应,请手动打开)</span></a> <div class='_toolTipClose' style='bottom: 10px;' onClick='_toolTipClose()'>取消</div> </div>
css部分测试
#_toolTipBox { display:none; width:100%; height:100%; background:rgba(0,0,0,0.4); position:fixed; top:0; left:0; z-index:90; transition:all 0.8s; } #_toolTip { display:none; position:fixed; transition:all 0.5s; line-height:60px; z-index:99; width:90%; text-align:center; margin:auto; left:0; right:0; bottom:10px; font-family:微软雅黑; border-radius:15px; color:#4d9dfe;font-size:16px; } #_toolTip ._tipText { background:#FFF; width:100%; height:60px; line-height:60px; border-bottom:1px solid #D1D1D3; color:#4d9dfe; border-radius:18px 18px 0 0; } #_toolTip ._tipCode { background:#FFF; border-bottom:1px solid #D1D1D3; } #_toolTip ._tipCopy { background:#FFF; border-bottom:1px solid #D1D1D3; cursor:pointer;} #_toolTip ._tipOpenAPP { background:#FFF; display:block; border-radius:0 0 18px 18px; text-decoration:none; color:#4d9dfe;} #_toolTip ._tipOpenAPP span { font-size:14px; color:#888;} #_toolTip ._toolTipClose { background:#FFF; border-radius:18px; margin-top:18px; cursor:pointer;}
js部分url
// 微信号复制 function copywx(){ //Range对象表明页面上的一段连续区域,经过Range对象,能够获取或修改页面上的任何区域, //建立一个空的Range对象 const range = document.createRange(); //Range对象的selectNode方法用于将Range对象的起点指定为某个节点的起点,将Range对象的终点指定为该节点的终点, //使Range对象所表明的区域中包含该节点。 range.selectNode(document.getElementById('wechatCode')); //在html5中,每个浏览器窗口及每个窗口中都有一个selection对象,表明用户鼠标在页面中所选取的区域, //(注意:通过测试IE9如下的浏览器不支持Selection对象), //能够经过以下语句建立selection对象; const selection = window.getSelection(); if(selection.rangeCount > 0) { //removeAllRanges()从当前selection对象中移除全部的range对象 selection.removeAllRanges(); //seletion.addRange(range)一个区域(Range)对象将被增长到选区(Selection)当中。 selection.addRange(range); // 拷贝当前选中内容到剪贴板。 document.execCommand('copy'); alert("微信号复制成功!"); }else { alert('微信号复制失败,请手动复制!'); } } /*打开弹窗*/ function _toolTipOpen() { document.getElementById('_toolTipBox').style.display = 'block'; document.getElementById('_toolTip').style.display = 'block'; }; /*关闭弹窗*/ function _toolTipClose() { document.getElementById('_toolTipBox').style.display = 'none'; document.getElementById('_toolTip').style.display = 'none'; }