Select a given line in a text area【在文本区域中选择给定的行】
Have you ever wanted to select a specific line in a text area using JavaScript DOM? This can come in handy when you need to highlight a particular line of text or copy it to the clipboard.【你是否有过想要使用JavaScript DOM在文本区域中选择特定行的经历?当你需要突出显示特定的文本行或将其复制到剪贴板时,这会非常有用。】
One real-life example where this technique might be useful is in building a code editor. 【这个技术可能有用的一个现实例子是构建代码编辑器】Code editors often have features that allow users to navigate through their code and highlight specific sections of it. By selecting a particular line, we can help users better visualize and understand their code, leading to a more seamless coding experience.【代码编辑器通常具有允许用户浏览代码并突出显示代码的特定部分的功能。通过选择特定的行,我们可以帮助用户更好地可视化和理解代码,从而获得更无缝的编码体验】 This functionality could also be helpful in creating chat applications where users may want to copy specific lines of conversation for reference or sharing purposes.【此功能在创建聊天应用程序时也可能非常有用,因为用户可能希望复制特定的对话行以供参考或共享。】
In this post, we'll dive into how to implement this functionality with JavaScript.
【在这篇文章中,我们将深入探讨如何使用JavaScript实现此功能。】
Retrieving the text area element【获取文本区域元素】
To get started, use the document.getElementById() method to retrieve the text area element. Simply pass in the ID of the text area element as an argument.【首先,使用document.getElementById()方法检索文本区域元素。只需将要检索的文本区域元素的ID作为参数传递即可。】
const textarea = document.getElementById('textarea');
Retrieving the beginning and ending indices of the line【检索行的开始索引和结束索引】
If you want to choose a particular line of text in the text area, you'll need to locate the beginning and end indices of that line. To achieve that, we need to retrieve the value of the text area and split it using the newline character (\n).【如果您想在文本区域中选择特定的文本行,则需要找到该行的起始和结束索引。为了实现这一点,我们需要检索文本区域的值并使用换行符(\n)对其进行拆分。】
To find the starting position of the selected line, we first create an array of zeros with the same length as the line's index. Then, we map this array to an array of line lengths (adding one for the newline character). Finally, we add up all the elements before the index of your selected line to get the start position.【为了找到所选行的起始位置,我们首先创建一个与行索引长度相同的零数组。然后,我们将此数组映射到行长度的数组(为换行符添加1)。最后,我们将所选行索引之前的所有元素相加,以得到起始位置。】
To determine the end position of your selection, add the length of the line you selected to its starting point. This will give you the index of the last character in your selection.【要确定所选内容的结束位置,请将所选行的长度添加到其起始点。这将给出所选内容中最后一个字符的索引。】
In the sample code provided, we're selecting the third line (index 2) of the text area element.
【在提供的示例代码中,我们选择了文本区域元素的第三行(索引为2)。】
const lines = textarea.value.split('\n');
// Select the third line (index 2)
const lineIndex = 2;
const start = Array(lineIndex)
.fill(0)
.map((_, i) => (lines[i].length + 1))
.reduce((a, b) => a + b, 0);
// Add the length of the previous lines and the newline character
const end = start + lines[lineIndex].length;
To simplify the calculation of the starting position, you can use the reduce() method instead of mapping and reducing. With reduce(), we can add up the lengths of each line up to the selected line's index. Then, we add one more character to account for the newline character.【为了简化起始位置的计算,您可以使用reduce()方法而不是映射和减少。使用reduce(),我们可以将每行的长度加到所选行的索引处。然后,我们再添加一个字符以考虑换行符。】
const start = lines.slice(0, lineIndex).reduce((acc, curr) => acc + curr.length + 1, 0);
Selecting the range【选择范围】
To set the selection range of a text area element to the start and end indices of a line, use the setSelectionRange() method. Just remember to call the focus() function first to ensure the text area element is properly focused before selecting the range.【要将文本区域元素的选定范围设置为行的起始和结束索引,请使用setSelectionRange()方法。只需记住首先调用focus()函数以确保在选定范围之前正确聚焦了文本区域元素。】
textarea.focus();
textarea.setSelectionRange(start, end);
Now, the third line of the text area element should be selected.
<textarea id="textarea">Was, spirit great moved spirit deep itself image, from have behold bearing doesn't wherein she'd very, day.
Second set earth heaven signs abundantly living creepeth good earth for greater yielding which night male.
Bring midst whales blessed, is.
From subdue.
Yielding.
Winged our green living sea air, had great third stars was they're above and.
Morning light make first and kind sixth they're fowl, there.
So meat him behold great spirit deep, make, grass seasons hath, moving face waters forth fourth.</textarea>
<p>
<button id="select-button">Select the third line</button>
</p>
document.addEventListener('DOMContentLoaded', () => {
const selectButton = document.getElementById('select-button');
selectButton.addEventListener('click', () => {
const textarea = document.getElementById('textarea');
const lines = textarea.value.split('\n');
const lineIndex = 2;
const start = lines.slice(0, lineIndex).reduce((acc, curr) => acc + curr.length + 1, 0);
// Add the length of the previous lines and the newline character
const end = start + lines[lineIndex].length;
textarea.focus();
textarea.setSelectionRange(start, end);
});
});
资料:
come in handy:派上用场
technique
n.
技巧;工艺;技术;技能;技艺
functionality
n.
(计算机或电子系统的)功能;实用;设计功能;设计目的;符合实际
reference
n.
参考,参照,查阅;(方便查询的)编号,标记,索引;关系,关联;(关于入学、谋职、信贷申请人品行、能力等情况的)查询;谈到,论及;提交仲裁,委托处理;(帮助或意见的)征求,征询;参考书目;(求职等时的)推荐人,介绍人,证明人;介绍信,推荐信;引文,引用的观点,参考章节,引证;(词与其所指对象之间的)相互关系,(词的)所指意义
vt.
提及;附(图表、资料等)以供参考;在(著作)末尾附加参考资料;提出或引用……作参考
adj.
参考的,参考用的;基准的,可作基准的
purposes
n.
目的;用途;目标;意图;重要意义;情势的需要;有价值的意义
v.
打算(purpose 的第三人称单数形式);企图
purpose的第三人称单数和复数
retrieving
v.
取回;检索数据;找回;挽回;索回;扭转颓势
retrieve的现在分词
particular
adj.
专指的,特指的(与泛指相对);讲究;格外的;挑剔;特别的;不寻常的
n.
详情;(正式记下的)细节;详细资料;详细介绍材料
achieve
v.
实现;(凭长期努力)达到(某目标、地位、标准);完成;成功
determine
v.
确定;测定;决定;决定,决心(做某事);影响;形成;安排;裁决;查明;支配;准确算出
calculation
n.
计算;预测;估计;推测;算计;自私的打算
account
n.
账户;账户,账号;解释,说明,叙述;账目;描述;赊购;老主顾;赊销账;赊欠账
vt.
认为是;视为
语雀翻译原文:www.yuque.com/fengjutian/… 《Select a given line in a text area【在文本区域中选择给定的行】》