一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

js实现文字选中分享功能

时间:2017-03-07 编辑:简简单单 来源:一聚教程网

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

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

 代码如下 复制代码

*{padding: 0;margin: 0;}

#p1{width: 300px;}

#div1{display: none;position: absolute;}

img{width:26px;height:26px;}

 文字的选中功能是不太常用的功能,多出现在文本编辑器中,或是文本域之类的光标处理上。所以呢,使用的一些属性也并不是常见的。在IE浏览器下使用的是createTextRange而Firefox/chrome等现代浏览器下使用的是setSelectionRange。

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';

}

热门栏目