首页 > 解决方案 > 基于光标检测句子

问题描述

$("#paragraph").html("<span>The Faculty Development Programme would enable identification and preparation of relevant course transaction resources.</span><span> These resources include Reference Books, Films, PPTs, Case Lets and Case Studies Work Education, Experiential Learning and its various aspects, Village Project Work and Field Work and Preparation of Village Social and Resource Maps.</span>");


function detectSentence(){
   //console.log("Iam here");
   if (window.getSelection && (sel = window.getSelection()).modify) {
       selection = window.getSelection();
       selection.extend (selection.focusNode.parentNode, 0);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div contenteditable="true" id="paragraph">
</div>
<br><br>
<button type="button" onclick="detectSentence()" id="btn">
Detect Sentence
</button>

我有一个包含一个段落的 div,这个段落可以有多个句子。我将这些句子包含在一个 span 标签中,以便将每个句子分开。因此,文本中已经确定了句子边界。现在当焦点在这个div的任何地方时,有没有办法检测光标所属的句子。

我曾尝试使用window.getSelection();,但无法获得如何使用此方法的解决方案。我的问题是有一种方法可以将选择移动到光标周围最近的开始和结束span标记,以便相应的句子将在光标所在的位置突出显示。

使用此代码段,我可以选择直到开始句子标签的文本,但未突出显示结束句子标签。要测试片段,请单击 div 中的任意位置,然后单击按钮 Detect Sentence。

标签: javascriptjquerycursorselection

解决方案


此代码为您提供元素光标位于或具有选定内容的元素。

$("#paragraph").html("<span>The Faculty Development Programme would enable identification and preparation of relevant course transaction resources.</span><span> These resources include Reference Books, Films, PPTs, Case Lets and Case Studies Work Education, Experiential Learning and its various aspects, Village Project Work and Field Work and Preparation of Village Social and Resource Maps.</span>");

detectSentence = function(){
   var node = document.getSelection().anchorNode;
   sentenceElem = node.nodeType == 3 ? node.parentNode : node;
   console.log(sentenceElem)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true" id="paragraph">
</div>
<br><br>
<button type="button" onclick="detectSentence()" id="btn">
Detect Sentence
</button>


推荐阅读