根据光标检测句子



$("#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();,但无法获得如何使用此方法的解决方案。我的问题是有没有办法将选择移动到光标周围最近的开始和结束span标签,以便在光标存在的地方突出显示相应的句子。

使用此代码段,我可以选择文本直到起始句子标签,但结尾句子标签未突出显示。要测试代码段,请单击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>

最新更新