[英]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.