2017-10-18 80 views
0

我有V-HTML标签呈现一个HTML文本并显示,就像这样:如何突出html标签内的字不突出标签VUE

<div v-html="htmlText"></div>
我写这篇文章的代码突出显示文本和它适用于普通的文本:

Vue.filter('highlight', function (word, query) { 
 
    if (query !== '') { 
 
    let check = new RegExp(query, "ig"); 
 
    return word.toString().replace(check, function (matchedText, a, b) { 
 
     return ('<strong class="mark">' + matchedText + '</strong>'); 
 
    }); 
 
    } else { 
 
    return word; 
 
}
<div v-html="$options.filters.highlight(htmlText, myWord)"> 
 
</div>

我想突出显示该文本中的一个单词而不突出显示html标记。 请帮忙。 谢谢。

+0

的可能的复制([只突出一个字符串(JQuery的/ JavaScript)的范围内匹配的文本] https://stackoverflow.com /问题/ 43328094 /高亮仅匹配文本中之串-jquery的JavaScript的)** **或[Vue的JS文本高亮显示过滤器(https://stackoverflow.com/questions/37839608/vue- js-text-highlight-filter) – ctwheels

+0

它不是重复的... –

+0

我的html文字是这样的:

hjbsdhbdhbvjvgfbhjduhsbcbvsdjbh
fuhsb
cdbh
vfshb

vfdvd

和无标签的具有特定的类或ID ... 他们是未知 –

回答

0

如果您不反对外部依赖关系,则可以使用mark.js

它允许使用RegExp突出显示文本,并且可以跨HTML标签工作。下面是它如何与Vue公司使用的例子:

var demo = new Vue({ 
 
    el: '#demo', 
 
    data: { 
 
    // The html to highlight 
 
    html: '<div>Hello <span>this </span>is <span>some </span>text</div>', 
 
    
 
    // The html with highlighting 
 
    highlightedHtml: '', 
 
    
 
    // The search term to highlight 
 
    search: 'Hello' 
 
    }, 
 
    watch: { 
 
    // When the search term changes: recalculate the highlighted html 
 
    'search': { 
 
     handler: function() { 
 
     \t // We create an element with the html to mark. Give it a unique id 
 
     // so it can be removed later 
 
     let id = 'id' + (new Date()).getTime(); 
 
     $('body').append(`<div id="${id}" style="hidden">${this.html}</div>`); 
 
     
 
     // Create a Mark instance on the new element 
 
     let markInstance = new Mark('#' + id); 
 
     
 
     // Mark the text with the search string. When the operation is complete, 
 
     // update the hightlighted text and remove the temporary element 
 
     markInstance.markRegExp(new RegExp(this.search, 'gmi'), { 
 
      done:() => { 
 
      this.highlightedHtml = $('#' + id)[0].innerHTML; 
 
      $('#' + id).remove(); 
 
      }, 
 
      acrossElements: true, 
 
     }); 
 
    \t }, 
 
     immediate: true 
 
    } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script> 
 
<script src="https://code.jquery.com/jquery-3.2.1.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.0/mark.js"></script> 
 

 
<div id="demo"> 
 
    <div>/ <input type="text" v-model="search"> /gmi</div> 
 
    <div v-html="highlightedHtml"></div> 
 
</div>