如何选择段落

时间:2016-04-27 10:10:24

标签: javascript jquery click textselection

我需要在段落中从当前单词到该句子的结尾点击实施按范围选择文字

例如:

  

Lorem Ipsum只是印刷和排版行业的虚拟文本。 Lorem Ipsum一直是......

是一个段落。当我点击虚拟时,选择将从虚拟到工业完成。以下代码使我能够单击选择完整的段落。

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <style type="text/css">
       p {
       font-family: monospace;
       font-size: 1.5em;
       }    
    </style>
   </head>

   <body>

      <div id="autoselect">
         <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
    when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, 
    remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing 
    software like Aldus PageMaker including versions of Lorem Ipsum.</p>
     </div>

 <script type="text/javascript">

  function SelectText(element) {
    var doc = document,
        text = doc.getElementById(element),
        range,
        selection;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
$(function() {

    $('p').click(function () {
        SelectText('autoselect');
    });

}); 

</script>
</body>

1 个答案:

答案 0 :(得分:0)

这个小提琴几乎可以满足您的需求。可能需要稍微调整一下,但它会从点击的单词中选择带有句点的第一个单词。处理空间可能很棘手,就像现在一样,它也会选择句点之后的空间。

https://jsfiddle.net/flatulentdog/86tfuff0/

  var words = $("p:first").text().split(" ");
  var text = words.join("</span> <span>");
  $("p:first").html("<span>" + text + "</span>");
  $("span").click(function () {
    $(this).css("background-color","yellow");
    var next = $(this).next();
    while(next.text().indexOf('.') === -1) {
        next.css("background-color","yellow");
        next = next.next();
    }
    next.css("background-color","yellow");
  });