如何使用javascript从iframe中选择文本? [英] how to get selected text from iframe with javascript?

查看:132
本文介绍了如何使用javascript从iframe中选择文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<html>
 <body>
  <script type="text/javascript">

   function smth() {

    if (document.getSelection) {
    var str = document.getSelection();
    if (window.RegExp) {
      var regstr = unescape("%20%20%20%20%20");
      var regexp = new RegExp(regstr, "g");
      str = str.replace(regexp, "");
    }
    } else if (document.selection && document.selection.createRange) {
     var range = document.selection.createRange();
     var str = range.text;
    }   

    alert(str);
   }
  </script>   

    <iframe id="my"  width="300" height="225">
   .....some html ....
    </iframe>      

    <a href="#" onclick="smth();">AA</a>
 </body>    
</html>

smth 功能我可以选择文字来自某个div,但它不适用于iframe。
如何从iframe中获取所选文本的任何想法?

with smth function i can get selected text from some div, but it doesnt work with iframe. any ideas how to get selected text from iframe ?

推荐答案


document.getSelection

document.getSelection

在外部文件上。要在iframe中选择文档,您需要获取内部文档:

Is on the outer document. To get the selection of the document in the iframe you need to grab the inner document:

var iframe= document.getElementById('my');
var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility

idoc.getSelection()

注意WebKit不支持 document.getSelection() document.selection 。尝试将其替换为 window.getSelection(),它可以在Firefox和WebKit中使用,但返回一个选择对象(Ranges周围的集合/包装),需要字符串:

Note however that WebKit does not support document.getSelection() or document.selection. Try replacing it with window.getSelection() which works in both Firefox and WebKit, but returns a selection object (a collection/wrapper around Ranges), which needs stringing:

var idoc= iframe.contentDocument || iframe.contentWindow.document;
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;

''+iwin.getSelection()

我不确定这是什么意思:

I'm not sure what the point of this is:

if (window.RegExp) {
  var regstr = unescape("%20%20%20%20%20");
  var regexp = new RegExp(regstr, "g");
  str = str.replace(regexp, "");
}

RegExp 是基本的JavaScript可以追溯到最早的版本;它永远存在,你不必嗅闻它。多个空格的URL编码是非常不必要的。你甚至不需要RegExp,字符串替换可以写成:

RegExp is basic JavaScript dating back to the very earliest version; it will always be there, you don't have to sniff for it. The URL-encoding of multiple spaces is quite unnecessary. You don't even need RegExp as such, a string replace could be written as:

str= str.split('     ').join('');

这篇关于如何使用javascript从iframe中选择文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆