显示突出显示的文字

时间:2018-04-09 01:59:27

标签: javascript jquery html

我是Javascript的新手。我一直在尝试在Web界面上添加突出显示功能,但努力让它正常工作。下面的代码是我到目前为止所获得的代码,它允许用户选择文本 - >然后出现弹出按钮以选择所选文本属于哪个类 - >选中的文字突出显示。但是这些突出显示的文字没有正确保存,因此,当"显示突出显示时,它们无法正确显示。单击按钮(如屏幕截图所示)。

在这个例子中,我希望看到

  

第1班:大律师康斯坦斯布里斯科

     

第2课:警察

当"显示亮点"点击。最终,这些突出显示的文本及其类将被保存为未来的序列(抱歉,我只熟悉Python)。

屏幕截图#1: highlighting screenshot 截图#2: show highlights screenshot

require(['jquery-noconflict'], function(jQuery) {
  var $ = jQuery || window.jQuery;
  var lastSelection;
  document.addEventListener("selectionchange", function() {
    lastSelection = window.getSelection()
  });
  var showBtn = document.getElementById('show_highlights_btn');
  var highlights = document.createElement("highlights") 

  function getRightClick(e) {return rightclick; // true or false
    }

    function getSelectionText() {return text;
    }


  $('.main_area').mousedown(function(event) {
    $('body').attr('mouse-top',event.clientY+window.pageYOffset);
    $('body').attr('mouse-left',event.clientX);

    if(!getRightClick(event)) {
            $('.entity_types').hide(); 
            document.getSelection().removeAllRanges(); 
        }
  });

  $('.main_area').mouseup(function(event) {
    if (lastSelection.toString().length > 1 && !getRightClick(event) ){
      $('.entity_types').css({
        display: 'block',
        position: 'absolute',
        top: event.clientY + 15,
        left: event.clientX + 10
      });

      $('.entity_types button').on('click', function(e) {
        e.preventDefault();
        var selectedText = getSelectionText();
        var category = $(this).text();
        var txt = document.createTextNode(category  + ": "  + selectedText);
        highlights.appendChild(txt);
      });
    }
  });

  showBtn.addEventListener('click', function () {
    //<div id="selected_highlights"></div>
    var selected_highlights = document.getElementById("selected_highlights");
    selected_highlights.appendChild(highlights);
  });

});

更新:我已成功制作了#34;展示精彩集锦&#34;工作,但不知何故最新亮点显示两次..

  showBtn.addEventListener('click', function () {
    console.log("display buttons");
    var selected_highlights = document.getElementById("selected_highlights");

    /** first remove current text **/
    while (selected_highlights.hasChildNodes()) {
      selected_highlights.removeChild(selected_highlights.lastChild);
    }

    for (i = 0; i < highlights.innerHTML.length; i++) {
      console.log('display highlight');
      selected_highlights.appendChild(highlights.childNodes[i]);
      selected_highlights.appendChild(br());
    }

2 个答案:

答案 0 :(得分:2)

首先,这是如何在HTML中突出显示文本。

&#13;
&#13;
<span style="background-color:#FFFF00">HIGHLIGHTED TEXT</span>
&#13;
&#13;
&#13;

因此,因为您将高亮颜色分为几类,所以您可以为每个范围指定类。

&#13;
&#13;
.class1{
background-color:red;
}
.class2{
background-color:green;
}
.class3{
background-color:blue;
}
.class4{
background-color:turquoise;
}
.class5{
background-color:purple;
}
&#13;
<span class='class1'>CLASS 1</span>
<span class='class2'>CLASS 2</span>
<span class='class3'>CLASS 3</span>
<span class='class4'>CLASS 4</span>
<span class='class5'>CLASS 5</span>
&#13;
&#13;
&#13;

现在,您需要获取所选文本。

&#13;
&#13;
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}
document.onmouseup = document.onkeyup = document.onselectionchange = function() {
  console.log(getSelectionText());
};
&#13;
.class1{
    background-color:red;
    }
    .class2{
    background-color:green;
    }
    .class3{
    background-color:blue;
    }
    .class4{
    background-color:turquoise;
    }
    .class5{
    background-color:purple;
    }
&#13;
<span class='class1'>CLASS 1</span>
    <span class='class2'>CLASS 2</span>
    <span class='class3'>CLASS 3</span>
    <span class='class4'>CLASS 4</span>
    <span class='class5'>CLASS 5</span>
&#13;
&#13;
&#13;

然后您获取该文本并突出显示该文本。 我在这个例子中通过用span替换单词来做到这一点,但这不是最好的方法。例如,在此突出显示&#34;短语&#34;将突出显示&#34;短语的第一个实例&#34;在书里。但这超出了当前的问题,所以我会把它留给你。

&#13;
&#13;
.class1{
background-color:red;
}
.class2{
background-color:green;
}
.class3{
background-color:blue;
}
.class4{
background-color:turquoise;
}
.class5{
background-color:purple;
}
&#13;
<span class='class1'>CLASS 1</span>
<span class='class2'>CLASS 2</span>
<span class='class3'>CLASS 3</span>
<span class='class4'>CLASS 4</span>
<span class='class5'>CLASS 5</span>
&#13;
&#13;
&#13;

现在,您需要获取所选文本,然后突出显示它。

&#13;
&#13;
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    console.log(text);
    return text;
}
function highlight(){
  if(getSelectionText().split(" ").length>1){
  document.getElementById("text").innerHTML=document.getElementById("text").innerHTML.replace(getSelectionText(), "<span class='class1'>"+getSelectionText()+"</span>");
}else{
console.log("TOO SHORT!");
}
}
&#13;
.class1{
    background-color:red;
    }
    .class2{
    background-color:green;
    }
    .class3{
    background-color:blue;
    }
    .class4{
    background-color:turquoise;
    }
    .class5{
    background-color:purple;
    }
&#13;
<p id="text">Lorem ipsum dolor. Sit amet amet. Lorem purus risus sed molestie aliquam. A ac nulla sit lacus turpis. Eleifend vel nascetur orci wisi eget. Laoreet nibh non nibh mi eget. Ligula consectetuer mauris ornare turpis molestiae magna mauris risus venenatis amet nascetur. Leo sed aliquam. Aliquam vivamus wisi at at vehicula. In quam praesent pharetra amet arcu. Lectus morbi velit vitae eligendi nibh imperdiet praesent suspendisse. Id scelerisque vel semper arcu dolor posuere nec elementum. Consequat bibendum fermentum. Nunc sed enim. Neque fermentum in. Nulla ornare imperdiet non dolor cursus condimentum ac tellus. Auctor vestibulum etiam scelerisque ullamcorper ut in inceptos porttitor. Commodo morbi turpis. Arcu dictum nostra nunc velit et ultrices nec suspendisse urna quam sed. Maecenas eget feugiat.</p>
<button onclick="highlight()">HIGHLIGHT</button>
&#13;
&#13;
&#13;

让用户选择一个类,并将其保存到字典中。

&#13;
&#13;
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    console.log(text);
    return text;
}
function highlight(){
document.getElementById("dict").innerHTML+=encodeURIComponent(getSelectionText())+", ";
  if(getSelectionText().split(" ").length>1){
  document.getElementById("text").innerHTML=document.getElementById("text").innerHTML.replace(getSelectionText(), "<span class='"+document.getElementById("class").value+"'>"+getSelectionText()+"</span>");
}else{
console.log("TOO SHORT!");
}
}
&#13;
.class1{
    background-color:red;
    }
    .class2{
    background-color:green;
    }
    .class3{
    background-color:blue;
    }
    .class4{
    background-color:turquoise;
    }
    .class5{
    background-color:purple;
    }
&#13;
<p id="text">Lorem ipsum dolor. Sit amet amet. Lorem purus risus sed molestie aliquam. A ac nulla sit lacus turpis. Eleifend vel nascetur orci wisi eget. Laoreet nibh non nibh mi eget. Ligula consectetuer mauris ornare turpis molestiae magna mauris risus venenatis amet nascetur. Leo sed aliquam. Aliquam vivamus wisi at at vehicula. In quam praesent pharetra amet arcu. Lectus morbi velit vitae eligendi nibh imperdiet praesent suspendisse. Id scelerisque vel semper arcu dolor posuere nec elementum. Consequat bibendum fermentum. Nunc sed enim. Neque fermentum in. Nulla ornare imperdiet non dolor cursus condimentum ac tellus. Auctor vestibulum etiam scelerisque ullamcorper ut in inceptos porttitor. Commodo morbi turpis. Arcu dictum nostra nunc velit et ultrices nec suspendisse urna quam sed. Maecenas eget feugiat.</p>
<input id="class" value="class1" /><button onclick="highlight()">HIGHLIGHT</button>
<p id="dict"></p>
&#13;
&#13;
&#13;

希望这有帮助!

答案 1 :(得分:1)

看看这对你有帮助,我几天前为朋友做了一个小提琴,

也许不是您的确切用例,但逻辑可能对您有帮助。

&#13;
&#13;
function highlightSearch() {

  var text = ["JavaScript", "is", "or"];
  
  var sampleText = document.getElementById('searchtext').innerHTML;
  //alert(sampleText);
  
  for(var i = 0; i<text.length; i++){
  	//console.log(text[i]);
    var re = new RegExp(text[i], 'g');
    sampleText = sampleText.replace(re, '<a href="#"><span class="highlighte-text">'+text[i]+'</span></a>');
    
    
  }
  
  document.getElementById('searchtext').innerHTML = sampleText;
  
  
}
&#13;
div {
    padding: 10px; 
}

.highlighte-text{
  background-color: skyblue;
}
&#13;
<div><h2>Find and highlight 'javascript', 'is' & 'or' text in document</h2>
<form action="" method="" id="search" name="search">

<input name="searchit" type="button" value="Search" onclick="highlightSearch()">
</form></div>
<div id="searchtext">
JavaScript is the programming language of the Web. The overwhelming majority of
modern websites use JavaScript, and all modern web browsers—on desktops, game
consoles, tablets, and smart phones—include JavaScript interpreters, making Java-
Script the most ubiquitous programming language in history. JavaScript is part of the
triad of technologies that all Web developers must learn: HTML to specify the content
of web pages, CSS to specify the presentation of web pages, and JavaScript to specify
the behavior of web pages. This book will help you master the language.
If you are already familiar with other programming languages, it may help you to know
that JavaScript is a high-level, dynamic, untyped interpreted programming language
that is well-suited to object-oriented and functional programming styles. JavaScript
derives its syntax from Java, its first-class functions from Scheme, and its prototypebased
inheritance from Self. But you do not need to know any of those languages, or
be familiar with those terms, to use this book and learn JavaScript.
The name "JavaScript" is actually somewhat misleading. Exceptfor a superficial syntactic
resemblance, JavaScript is completely different from the Java programming language.
And JavaScript has long since outgrown its scripting-language roots to become
a robust and efficient general-purpose language. The latest version of the language (see
the sidebar) defines new features for serious large-scale software development.
</div>
&#13;
&#13;
&#13;