gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:38:41 24 4
gpt4 key购买 nike

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

以下代码用于文本选择

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>

Javascript 与 JQuery:

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. Get the selection text.
  2. Go through the original text contained in the html element and use custom made logic to get the next sentence. (In this example, "." is the mark of the end of sentences).

仅供引用,发布的代码是

的扩展版本
http://jsfiddle.net/abdennour/BQSJ3/6/

向原创者致敬。

希望有帮助。谢谢

关于javascript - 如何在javascript中选择未选定的文本和选定的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26368100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com