一个类似百度文库选中弹出个小框的效果
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- 2 transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/xhtml"> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 6 <title>JS获得鼠标位置</title> 7 <script src="jquery-1.8.3.js" type="text/javascript"></script> 8 </head> 9 <body> 10 <script> 11 function mouseCoords(ev) 12 { 13 if(ev.pageX || ev.pageY){ 14 return {x:ev.pageX, y:ev.pageY}; 15 } 16 return { 17 x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, 18 y:ev.clientY + document.body.scrollTop - document.body.clientTop 19 }; 20 } 21 function funcGetSelectText(){ 22 var txt = ''; 23 if(document.selection){ 24 txt = document.selection.createRange().text;//ie 25 }else{ 26 txt = document.getSelection(); 27 } 28 return txt.toString(); 29 } 30 $(function(){ 31 32 var container = container || document; 33 container.onmouseup = function(ev){ 34 var txt = funcGetSelectText(); 35 if(txt) 36 { 37 alert("搜索关键字:"+txt); 38 ev= ev || window.event; 39 var mousePos = mouseCoords(ev); 40 var posX = mousePos.x+10; 41 var posY = mousePos.y+5; 42 $("#test").css({"position":"absolute","left":posX,"top":posY,"display":"block"}); 43 $("#test").html(txt); 44 } 45 else 46 { 47 $("#test").css("display","none"); 48 } 49 } 50 51 52 53 }); 54 </script> 55 <script> 56 57 58 </script> 59 <div id="str" style="width: 100%;height: 100%;">百度测试百度测试百度测试啊百度测试啊百度测试啊百度测试啊百度测试啊百度测试啊</div> 60 <div id='test' style="width: 200px;height: 25px; background-color: red;display: none;"><a href="www.baidu.com"></a></div> 61 </body>
思路是:鼠标抬起是获取到鼠标的位置,和选中的内容,然后根据这个位置给div一个绝对定位