javascript用createRange拷贝Range片段到粘贴板(代码实例)
程序员文章站
2022-06-19 23:11:36
最近项目需要做一个编辑器,其中有个按钮点击可以将编辑好的文章一键复制到粘贴板,产品的要求是复制好的文章能连带图片和样式一起粘贴到word中。本来打算用clipboard.js来做的,但发现它只能复制...
最近项目需要做一个编辑器,其中有个按钮点击可以将编辑好的文章一键复制到粘贴板,产品的要求是复制好的文章能连带图片和样式一起粘贴到word中。本来打算用clipboard.js来做的,但发现它只能复制文本。
在谷歌之后,有了新的方案:利用range对象选择需要复制的范围,然后将选好的范围复制下来。
我用layui的define方法封装了一个对象
layui.define(['jquery','layer'],function(exports){ var $=layui.jquery var layer=layui.layer var obj={ __issupport:function(){ var supportsrange=document.implementation.hasfeature("range","2.0"); var alsosupportsrange=(typeof document.createrange == 'function') var supportsselection=(typeof window.getselection == 'function') var supportsexeccommand=(typeof document.execcommand == 'function') var result=supportsrange && alsosupportsrange && supportsselection && supportsexeccommand; if(!result){ layer.alert('您的浏览器版本不支持范围复制,请手动复制或换高版本浏览器') } return result; }, __simple:function(selector,type){ var self=this; var node,range,selection; if(!self.__issupport()){ return; } node=$(selector)[0] range=document.createrange() if(type=='node'){ range.selectnode(node); }else if(type=="nodecontents"){ range.selectnodecontents(node) } selection=window.getselection() selection.empty(); selection.addrange(range); document.execcommand('copy') selection.empty(); range.detach() range=null }, //拷贝节点 node:function(selector){ var self=this; self.__simple(selector,'node') }, //拷贝节点的内容 nodecontents:function(selector){ var self=this; self.__simple(selector,'nodecontents') } } exports('copy',obj) })
这个是需要依赖layui的,后面有空撸个不依赖任何js库的。