最近项目中需要点复制功能,然后百度了一下网上各种方法,有的参考插件(不太理想,一个功能参考一个插件,代码太冗余),还有自封装的(可能是技术发展比较快,有些是无效的),但是根据他们的介绍,我找到了相关的API,总结了一下,适用于ChromeFirefox(Gecko)上网Explorer(9+)OperaSafari方法一:使用Selection和Range对象第一步创建Range对象letrange=document.createRange()//传入要选择的元素节点range.selectNodeContents(Nodenode)创建aSelection对象varselection=document.getSelection()//清除选中区域selection.removeAllRanges()//添加选中区域selection.addRange(range)callscopydocument.execCommand('Copy')CodefunctioncopyHandler(node){letrange=document.createRange()range.selectNodeContents(node)让选择=文档。getSelection()selection.removeAllRanges()selection.addRange(range)document.execCommand('Copy')}方法二:使用input和textarea元素的select()方法缺点是需要创建冗余标签,input和textarea必须是displayed,设置以下任何一种样式都行不通:display:nonevisibility:hiddenwidth:0height:0或者直接在代码上看html
