js实现文字选中分享功能

总结:文字选中IE和其他浏览器不一样

在IE中文字选中后鼠标抬起,图片显现触发有点快所以用定时器。

<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <script type="text/javascript" src="https://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> <style type="text/css"> *{padding: 0;margin: 0;} #p1{width: 300px;} #div1{display: none;position: absolute;} img{width:26px;height:26px;} </style> </head> <body> <p> 文字的选中功能是不太常用的功能,多出现在文本编辑器中,或是文本域之类的光标处理上。所以呢,使用的一些属性也并不是常见的。在IE浏览器下使用的是createTextRange而Firefox/chrome等现代浏览器下使用的是setSelectionRange。 </p> <div><img src='https://cdn.attach.qdfuns.com/notes/pics/201701/23/221744ud9ggjjjgg85e90m.gif.editor.gif'></div> <script type="text/javascript"> function selectText(){ if(document.selection){ //IE return document.selection.createRange().text }else{ //ff chrom return window.getSelection().toString() } } var oP=document.getElementById('p1') var oDiv=document.getElementById('div1') oP.onmouseup=function(ev){ var ev=ev||event var left=ev.clientX var top=ev.clientY if(selectText().length>10){ setTimeout(function(){ oDiv.style.display='block'; oDiv.style.left=left+'px' oDiv.style.top=top+'px' },100) }else{ oDiv.style.display='none'; } } //点击oP阻止冒泡到document上 oP.onclick=function(ev){ var ev=ev||window.event ev.cancelBubble=true } document.onclick=function(){ oDiv.style.display='none'; } </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwgpjg.html