如何在javascript中选择未选中的文本和选中的文本

How to select unselected text along with selected text in javascript?

本文关键字:文本 选择 javascript      更新时间:2023-09-26

我正在开发一个应用程序,该应用程序需要选择下一行和所选行。

以下代码用于文本选择

function getSelectedText() {
        var text = "";
        if (typeof window.getSelection != "undefined") {
            text = window.getSelection().toString();
        } else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
            text = document.selection.createRange().text;
        }
        //        alert('text = ' + text);
        return text;
    }

如何在javascript中选择下一行文本和所选行?

这可能会帮助您了解如何实现这一点:

HTML:

<body>
<pre>  
     Hahahaa. Jacko. Superman. Hulk.
     </pre>

 </body>

带有JQuery:的Javascript

function getSelectionTextWithNext() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    var preText = $("pre").text();
    var theBeginningTextIndex = preText.indexOf(text) + text.length;
    var preTextIndex = preText.indexOf('.', theBeginningTextIndex);
    var nextSentence = preText.substring(preText.indexOf(text), preTextIndex + 1);
    console.log(nextSentence);
    return nextSentence;
}
$(document).ready(function (){
   $('pre').mouseup(function (e){
       getSelectionTextWithNext();
   })
});

现场演示:

function getSelectionTextWithNext() {
  var text = "";
  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
  }
  var preText = $("pre").text();
  var theBeginningTextIndex = preText.indexOf(text) + text.length;
  var preTextIndex = preText.indexOf('.', theBeginningTextIndex);
  var nextSentence = preText.substring(preText.indexOf(text), preTextIndex + 1);
  console.log(nextSentence);
  return nextSentence;
}
$(document).ready(function() {
  $('pre').mouseup(function(e) {
    getSelectionTextWithNext();
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <pre>  
    Hahahaa. Jacko. Superman. Hulk.
    </pre>
</body>

样本会发现"."是句子结尾的标记。这个样本可能也有问题,但希望它能给你一些想法。

伪代码:

  1. 获取选择文本
  2. 浏览html元素中包含的原始文本,并使用自定义逻辑获得下一个句子。(在本例中,"."是句子结尾的标记)

FYI,张贴的代码是的扩展版本

http://jsfiddle.net/abdennour/BQSJ3/6/

向原创致敬。

希望能有所帮助。感谢