基于光标检测句子

detect sentence based on cursor

$("#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,里面有一个段落,这个段落可以有1个以上的句子。我将这些句子包含在一个 span 标记中,以便将每个句子分开。所以句子边界已经在文本中确定了。现在当焦点在这个div中的任何地方时,有没有办法检测光标所属的句子

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

使用此代码段,我可以 select 文本开始句子标记,但结束句子标记未突出显示。要测试代码段,请单击 div 中的任意位置,然后单击“检测句子”按钮。

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

$("#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>