繁体   English   中英

如何在html标签中突出显示单词而不在vue中突出显示标签

[英]how to highlight a word inside html tags without highlighting tags in vue

我有一个带有v-html的标签,该标签呈现html文本并显示它,如下所示:

 <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标签。 请帮忙。 谢谢。

如果您不反对外部依赖关系,则可以使用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() { // 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, }); }, 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM