3

このコードを使用して、ウィンドウ ドキュメントからテキストを選択しています。このコードはすべてのブラウザーで正常に機能します。選択したテキストを返しますが、IE8 では選択したテキストを返しません。代わりに、選択した行の HTML 全体を提供します。誰でもこれに対する解決策を教えてもらえますか?

例:

<B><U><SPAN style="LINE-HEIGHT: 150%; FONT-FAMILY: 'Arial',
'sans-serif'; FONT-SIZE: 12pt">Summary</SPAN></U></B> 

概要のみが必要なので、IE8 を除くすべての主要なブラウザーがこれを返します。

<script type="text/javascript">
    function getSelectionText(id) {
        var html = "";
        if (typeof window.getSelection != "undefined") {
            var sel = window.getSelection();
            if (sel.rangeCount) {
                var container = document.createElement("div");
                for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                    container.appendChild(sel.getRangeAt(i).cloneContents());
                }
                html = container.innerHTML;
            }
        } else if (typeof document.selection != "undefined") {
            if (document.selection.type == "Text") {
                html = document.selection.createRange().htmlText;
            }
        }
        document.getElementById(id).value = html;
        //document.getElementById(id).value = html;
    }       
</script>
4

3 に答える 3

0

問題はIE8の次の行にあります

html = document.selection.createRange().htmlText;

これに変更

html = document.selection.createRange().text;

以下は、私にとってうまくいくと思われる素敵なシンプルな関数です

function getSelectedText() {
  var txt = '';
  if (window.getSelection) {
    txt = window.getSelection();
  }
  else if (document.getSelection) {
    txt = document.getSelection();
  }
  else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  else return; 
  return txt;
}

お役に立てれば

于 2013-05-09T10:05:44.757 に答える