用jQuery突出显示一个单词 [英] Highlight a word with jQuery

查看:90
本文介绍了用jQuery突出显示一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上需要突出显示一段文字中的特定单词。例如,假装我想在本文中突出显示单词dolor:

 < p> 
Lorem ipsum dolor sit amet,consectetuer adipiscing elit。
< / p>
< p>
Quisque bibendum sem ut lacus。 Integer dolor ullamcorper libero。
在augue的Aliquam rhoncus eros。拖延mauris。
< / p>

如何将上述内容转换为这样的内容:

 < p> 
Lorem ipsum< span class =myClass> dolor< / span>坐在amet,consectetuer adipiscing elit。
< / p>
< p>
Quisque bibendum sem ut lacus。整数< span class =myClass>多乐< / span> ullamcorper
libero。 Aliquam rhoncus eros在augue。拖延mauris。
< / p>

这对jQuery来说可能吗?

修改:由于塞巴斯蒂安 指出,如果没有jQuery,这很有可能 - 但我希望可能有一种特殊的jQuery方法,它可以让你在选择器上进行选择文本本身。我已经在这个网站上大量使用了jQuery,所以把所有东西都包装在jQuery中会让事情变得更加整洁。 解决方案

尝试突出显示:JavaScript文本higlighting jQuery插件

  / * 

突出显示v4

突出显示任意条款。

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

MIT许可证。

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; (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;
}
返回this.length&&拍拍&& 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();
};

另请尝试updated版本的原始脚本

  / * 
* jQuery突出显示插件
*
*根据突出显示v3作者:Johann Burkard
* http://johannburkard.de/blog/programming/javascript/highlight-javascript- text-higlighting-jquery-plugin.html
*
*代码有点重构和清理(以我的愚见)。
*最重要的变化:
* - 可以选择仅突出显示整个单词(默认情况下,wordsOnly - false),
* - 可以选择区分大小写(caseSensitive - 默认为false )
* - 高亮元素标记和类名可以在选项中指定
*
*用法:
* //在内容$ b $中包装文本'lorem' b * //带< span class ='highlight'> (默认选项)
* $('#content')。highlight('lorem');
*
* //一次搜索并突出显示更多条款
* //这样您可以节省一些时间来遍历DOM
* $('#content')。highlight (['lorem','ipsum']);
* $('#content')。highlight('lorem ipsum');
*
* //只搜索整个单词'lorem'
* $('#content')。highlight('lorem',{wordsOnly:true});
*
* //在搜索词'lorem'
* $('#content')。'时忽略大小写。'highlight('lorem',{caseSensitive:true});
*
* //将内容
* //中的每个术语'ipsum'包括在< em class ='important'>
* $('#content')。highlight('ipsum',{element:'em',className:'important'});
*
* //删除默认突出显示
* $('#content')。unhighlight();
*
* //移除自定义高亮
* $('#content')。unhighlight({element:'em',className:'important'});
*
*
*版权所有(c)2009 Bartek Szopka
*
*根据MIT许可证授权。



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; //跳过添加的节点父节点
}
} else if((node.nodeType === 1&& node.childNodes)&&&& //仅有子节点
!/(脚本| style)/i.test(node.tagName)&&&& //忽略脚本和样式e节点
!(node.tagName === nodeName.toUpperCase()&& node.className === className)){//如果已经突出显示
,则跳过(var i = 0; i< node.childNodes.length; i ++){
i + = jQuery.highlight(node .childNodes [i],re,nodeName,className);
}
}
返回0;
}
});

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

返回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(设置,选项);

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? : 一世;
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);
});
};


I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:

<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>

How do I convert the above to something like this:

<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>

Is this possible with jQuery?

Edit: As Sebastian pointed out, this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.

解决方案

Try highlight: JavaScript text higlighting jQuery plugin.

/*

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();
};

Also try the "updated" version of the original script.

/*
 * 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);
    });
};

这篇关于用jQuery突出显示一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆