jQuery--计算选中的文本字数,并弹出一个层(插件四)
(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]