根据光标检测句子

时间:2019-01-10 11:33:37

标签: javascript jquery cursor selection

$("#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中的任意位置单击,然后单击“检测句子”按钮。

1 个答案:

答案 0 :(得分:1)

此代码使您可以打开元素光标或具有选定内容的元素。

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

相关问题