(function($){ $.fn.extend({ "selectText":function(value){ value=$.extend({ "delays":800 },value); var $this = $(this); //鼠标抬起进,获取选择文字的字数。并根据字数,是否显示弹出层 $this.mouseup(function(event){ //IE和火狐兼容性的处理函数。 function selectText(){ if(document.selection){ return document.selection.createRange().text;// IE }else{ return window.getSelection().toString(); //标准 } } var str = selectText(); var l = event.clientX; var t = event.clientY; if(str.length > 10){ $this.next("div").css({"top":t+10,"left":l+10}).delay(value.delays).fadeIn(); } }); //点击文档任何位置,让显示的层消失 $(document).click(function(){ $this.next("div").fadeOut(); }) //阻止冒泡,防止第一次选中文字时,由于冒泡,而触发了$(document).click事件 $this.click(function(event){ event.stopPropagation(); }); return $this; } }) })(jQuery)
关键:如何获取鼠标选中了多少个文字?
document.selection.createRange().text; IE使用
window.getSelection().toString(); 标准浏览器使用
注意
1.发生的事件,应该是mouseup,而不是select,这个只能用在输入元素里面例如input textarear;
2.阻止冒泡,防止第一次选中文字时,由于冒泡,而触发了$(document).click事件
[下载 DEMO]
鼠标选中文本检测与操作
本文介绍了一种使用jQuery实现的鼠标选中文本检测方法,通过监听mouseup事件,兼容IE和其他标准浏览器,实现了对选中文字数量的检测,并根据选中文字长度决定是否显示弹出层。
1984

被折叠的 条评论
为什么被折叠?



