Discuz教程网

JavaScript 选中文字并响应获取的实现代码

[复制链接]
authicon dly 发表于 2011-9-8 16:15:56 | 显示全部楼层 |阅读模式
本人不怎么会写JS,但是会搜索,这里找到了些别人写好的东西:
  1. select(document, tanchu);
  2. /*=select[[
  3. *
  4. * 跨浏览器选中文字事件
  5. * @param
  6. * object o 响应选中事件的DOM对象,required
  7. * function fn(sText,target,mouseP)选中文字非空时的回调函数,required
  8. * |-@param
  9. * |-sText 选中的文字内容
  10. * |-target 触发mouseup事件的元素
  11. * |-mouseP 触发mouseup事件时鼠标坐标
  12. */
  13. function select(o, fn){
  14. o.onmouseup = function(e){
  15. var event = window.event || e;
  16. var target = event.srcElement ? event.srcElement : event.target;
  17. if (/input|textarea/i.test(target.tagName) && /firefox/i.test(navigator.userAgent)) {
  18. //Firefox在文本框内选择文字
  19. var staIndex=target.selectionStart;
  20. var endIndex=target.selectionEnd;
  21. if(staIndex!=endIndex){
  22. var sText=target.value.substring(staIndex,endIndex);
  23. fn(sText,target);
  24. }
  25. }
  26. else{
  27. //获取选中文字
  28. var sText = document.selection == undefined ? document.getSelection().toString():document.selection.createRange().text;
  29. if (sText != "") {
  30. //将参数传入回调函数fn
  31. fn(sText, target);
  32. }
  33. }
  34. }
  35. }
  36. /*]]select=*/
  37. function tanchu(txt,tar){
  38. alert("文字属于"+tar.tagName+"元素,选中内容为:"+txt);
  39. }
复制代码

 原作者见:http://momomolice.com/wordpress/archives/420.html


附:只获得选取的文字的代码(不响应该事件)
  1. function getSelectedText()
  2. {
  3. if (window.getSelection)
  4. { // This technique is the most likely to be standardized.
  5. // getSelection() returns a Selection object, which we do not document.
  6. return window.getSelection().toString();
  7. }
  8. else if (document.getSelection)
  9. {
  10. // This is an older, simpler technique that returns a string
  11. return document.getSelection();
  12. }
  13. else if (document.selection)
  14. {
  15. // This is the IE-specific technique.
  16. // We do not document the IE selection property or TextRange objects.
  17. return document.selection.createRange().text;
  18. }
  19. }
复制代码

函数运行后会将选取的文字返回出来。  

原作者已不可考。。。



上一篇:js预载入和JavaScript Image()对象使用介绍
下一篇:IE6、IE7中获取Button元素的值的bug说明
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-3 07:28

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表