[javascript] jQuery로 단어 강조

기본적으로 텍스트 블록에서 특정 단어를 강조 표시해야합니다. 예를 들어,이 텍스트에서 “고통”이라는 단어를 강조하고 싶다고 가정 해보십시오.

<p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

위의 내용을 다음과 같이 어떻게 변환합니까?

<p>
    Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper
    libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

jQuery로 가능합니까?

편집 : Sebastian이 지적했듯이 이것은 jQuery 없이도 가능하지만 텍스트 자체에서 선택기를 할 수있는 jQuery의 특별한 방법이 있기를 바랐습니다. 나는 이미이 사이트에서 jQuery를 많이 사용하고 있기 때문에 모든 것을 jQuery로 묶어두면 아마도 좀 더 깔끔해질 것이다.



답변

시도 강조 : 자바 스크립트 텍스트가 jQuery 플러그인을 강조 .! 경고-이 페이지에서 사용 가능한 소스 코드에는 암호화 통화 마이닝 스크립트가 포함되어 있습니다. 아래 코드를 사용하거나 웹 사이트에서 다운로드 한 마이닝 스크립트를 제거하십시오. !

/*

highlight v4

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

*/

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

또한 원본 스크립트“업데이트 된”버전을 사용해보십시오 .

/*
 * jQuery Highlight plugin
 *
 * Based on highlight v3 by Johann Burkard
 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
 *
 * Code a little bit refactored and cleaned (in my humble opinion).
 * Most important changes:
 *  - has an option to highlight only entire words (wordsOnly - false by default),
 *  - has an option to be case sensitive (caseSensitive - false by default)
 *  - highlight element tag and class names can be specified in options
 *
 * Usage:
 *   // wrap every occurrance of text 'lorem' in content
 *   // with <span class='highlight'> (default options)
 *   $('#content').highlight('lorem');
 *
 *   // search for and highlight more terms at once
 *   // so you can save some time on traversing DOM
 *   $('#content').highlight(['lorem', 'ipsum']);
 *   $('#content').highlight('lorem ipsum');
 *
 *   // search only for entire word 'lorem'
 *   $('#content').highlight('lorem', { wordsOnly: true });
 *
 *   // don't ignore case during search of term 'lorem'
 *   $('#content').highlight('lorem', { caseSensitive: true });
 *
 *   // wrap every occurrance of term 'ipsum' in content
 *   // with <em class='important'>
 *   $('#content').highlight('ipsum', { element: 'em', className: 'important' });
 *
 *   // remove default highlight
 *   $('#content').unhighlight();
 *
 *   // remove custom highlight
 *   $('#content').unhighlight({ element: 'em', className: 'important' });
 *
 *
 * Copyright (c) 2009 Bartek Szopka
 *
 * Licensed under MIT license.
 *
 */

jQuery.extend({
    highlight: function (node, re, nodeName, className) {
        if (node.nodeType === 3) {
            var match = node.data.match(re);
            if (match) {
                var highlight = document.createElement(nodeName || 'span');
                highlight.className = className || 'highlight';
                var wordNode = node.splitText(match.index);
                wordNode.splitText(match[0].length);
                var wordClone = wordNode.cloneNode(true);
                highlight.appendChild(wordClone);
                wordNode.parentNode.replaceChild(highlight, wordNode);
                return 1; //skip added node in parent
            }
        } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
            for (var i = 0; i < node.childNodes.length; i++) {
                i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
            }
        }
        return 0;
    }
});

jQuery.fn.unhighlight = function (options) {
    var settings = { className: 'highlight', element: 'span' };
    jQuery.extend(settings, options);

    return this.find(settings.element + "." + settings.className).each(function () {
        var parent = this.parentNode;
        parent.replaceChild(this.firstChild, this);
        parent.normalize();
    }).end();
};

jQuery.fn.highlight = function (words, options) {
    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
    jQuery.extend(settings, options);

    if (words.constructor === String) {
        words = [words];
    }
    words = jQuery.grep(words, function(word, i){
      return word != '';
    });
    words = jQuery.map(words, function(word, i) {
      return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    });
    if (words.length == 0) { return this; };

    var flag = settings.caseSensitive ? "" : "i";
    var pattern = "(" + words.join("|") + ")";
    if (settings.wordsOnly) {
        pattern = "\\b" + pattern + "\\b";
    }
    var re = new RegExp(pattern, flag);

    return this.each(function () {
        jQuery.highlight(this, re, settings.element, settings.className);
    });
};


답변

function hiliter(word, element) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span class="myClass">' + word + '</span>';
    element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
hiliter('dolor');


답변

직접 만든 하이라이트 기능을 사용하는 것이 나쁜 생각 인 이유

처음부터 자신 만의 하이라이트 기능을 구축하는 것이 좋지 않은 이유는 다른 사람들이 이미 해결 한 문제에 부딪 힐 것이기 때문입니다. 과제 :

  • DOM 이벤트를 파괴하지 않고 DOM 재생성을 반복적으로 트리거하지 않고 일치 항목을 강조하기 위해 HTML 요소가있는 텍스트 노드를 제거해야합니다 (예 :이 경우 innerHTML).
  • 강조 표시된 요소를 제거하려면 콘텐츠와 함께 HTML 요소를 제거하고 추가 검색을 위해 분할 된 텍스트 노드를 결합해야합니다. 이는 모든 하이 라이터 플러그인이 텍스트 노드 내부에서 일치를 검색하고 키워드가 여러 텍스트 노드로 분할되면 찾을 수 없기 때문에 필요합니다.
  • 또한 생각하지 않은 상황에서 플러그인이 작동하는지 확인하기 위해 테스트를 빌드해야합니다. 그리고 저는 브라우저 간 테스트에 대해 이야기하고 있습니다!

복잡하게 들리나요? 강조 표시, 분음 부호 매핑, 동의어 매핑, iframe 내부 검색, 분리 된 단어 검색 등에서 일부 요소를 무시하는 것과 같은 일부 기능을 원하는 경우 이는 점점 더 복잡해집니다.

기존 플러그인 사용

잘 구현 된 기존 플러그인을 사용할 때 위에 언급 된 것에 대해 걱정할 필요가 없습니다. Sitepoint 의 기사 10 jQuery 텍스트 하이 라이터 플러그인은 인기있는 하이 라이터 플러그인 을 비교합니다. 여기에는이 질문의 답변 플러그인이 포함됩니다.

mark.js 살펴보기

mark.js 는 순수한 JavaScript로 작성된 플러그인이지만 jQuery 플러그인으로도 사용할 수 있습니다. 다음과 같은 옵션이있는 다른 플러그인보다 더 많은 기회를 제공하도록 개발되었습니다.

  • 전체 용어 대신 개별적으로 키워드 검색
  • 지도 분음 부호 (예 : “justo”가 “justò”와 일치해야하는 경우)
  • 맞춤 요소 내 일치 무시
  • 맞춤 강조 표시 요소 사용
  • 사용자 지정 강조 표시 클래스 사용
  • 맞춤 동의어 매핑
  • iframe 내에서도 검색
  • 찾을 수없는 용어 받기

데모

또는 이 바이올린을 볼 수 있습니다 .

사용 예 :

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

GitHub에서 무료로 개발 된 오픈 소스입니다 ( 프로젝트 참조 ).


답변

다음은 대소 문자를 무시하고 보존하는 변형입니다.

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp("\\b"+str+"\\b", "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};


답변

다음 기능 을 사용 하여 텍스트의 모든 단어를 강조 표시 할 수 있습니다 .

function color_word(text_id, word, color) {
    words = $('#' + text_id).text().split(' ');
    words = words.map(function(item) { return item == word ? "<span style='color: " + color + "'>" + word + '</span>' : item });
    new_words = words.join(' ');
    $('#' + text_id).html(new_words);
    }

간단히 요소 대상 텍스트를 포함 단어 선택 색상 화와 색상 선택을.

다음은 예입니다 .

<div id='my_words'>
This is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.
</div>

사용법 ,

color_word('my_words', 'possible', 'hotpink')

여기에 이미지 설명 입력

Azle 은 이것에 대한 좋은 기능도 가지고 있습니다. 클래스를 사용하므로 대상으로 지정하려는 텍스트 블록에 클래스 이름을 지정하기 만하면됩니다.

az.style_word("target_class", target_instance, {
     "this_class" : "pink_word",
     "word" : "possible", // list any CSS styling after this line ...
     "color" : "hotpink", 
     "font-weight" : "bold"
})


답변

정규식과 함께 작동 할 수있는 하이라이트 플러그인 jQuiteLight 를 사용할 수 있습니다.

npm 유형을 사용하여 설치하려면 :

npm install jquitelight --save

bower 유형을 사용하여 설치하려면 :

bower install jquitelight 

용법:

// for strings
$(".element").mark("query here");
// for RegExp
$(".element").mark(new RegExp(/query h[a-z]+/));

여기에 고급 사용법


답변

JSFiddle

.each (), .replace (), .html ()을 사용합니다. jQuery 1.11 및 3.2로 테스트되었습니다.

위의 예에서 강조 표시 할 ‘keyword’를 읽고 ‘highlight’클래스와 함께 span 태그를 추가합니다. .each ()에서 선택한 모든 클래스에 대해 ‘키워드’텍스트가 강조 표시됩니다.

HTML

<body>
   <label name="lblKeyword" id="lblKeyword" class="highlight">keyword</label>
   <p class="filename">keyword</p>
   <p class="content">keyword</p>
   <p class="system"><i>keyword</i></p>
</body>

JS

$(document).ready(function() {
   var keyWord = $("#lblKeyword").text();
   var replaceD = "<span class='highlight'>" + keyWord + "</span>";
   $(".system, .filename, .content").each(function() {
      var text = $(this).text();
      text = text.replace(keyWord, replaceD);
      $(this).html(text);
   });
});

CSS

.highlight {
    background-color: yellow;
}