之前悬赏过,因为第一次用这个平台,没有完全测试就给钱了,现在还是存在问题,主要问题是用的highlight问题,单个单词标记完保存会相同的单词都会自动标记,我们需要只定位这一个单词,希望不高改动这个插件等。
9条回答 默认 最新
CSDN专家-showbo 2022-08-17 10:13关注简单示例如下
<style> .highlight{background:yellow;display:inline!important} </style> <div id="highlight"> <!--需要高亮的单词放到id为highlight的容器里面--> <p>To promote tourism recovery and reconnect stakeholders, ITE - Hong Kong’s only travel fair, will be held from 18-21 August 2022 in HKCEC with scale bigger than in 2021! Its first 1.5 days open only to registered trade while in remaining sessions, visitors can pay at entrance for admission. Exhibiting and Visiting are welcome!</p> <p>Despite increased coverage on local travel, ITE2022 remains highly international! Of its 100 plus exhibitors, which include tourism authorities and enterprises, some 60% from abroad, which still significant but lower than the 85% in pre-pandemic year.</p> <p>The latest list of participating countries and regions include the mainland, Hong Kong, Japanese prefectures, Macau, Taiwan, Thailand, Canada, South Korea, Iceland, Spain and more.</p> </div> <input type="button" value="高亮选中单词" onclick="setHighlight()" /> <input type="button" value="清除所有高亮单词" onclick="clearHighlight()" /> <input type="button" value="保存高亮单词" onclick="saveHighlightWords()" /> <input type="button" value="高亮上次选中的单词" onclick="startHightlight()" /> <br />刷新后自动高亮,去掉代码最后一句的注释。 <script> function saveHighlightWords(notAlert) { words = words localStorage.setItem('words', JSON.stringify(words.sort((a, b) => b.length - a.length))); if (!notAlert)alert('保存成功,刷新页面后点击按钮加载高亮单词重试!') } function clearHighlight() { words = []; saveHighlightWords(1); var sps = highlight.querySelectorAll('span.highlight'); for (var sp of sps) { var textNode = document.createTextNode(sp.innerText); sp.parentNode.replaceChild(textNode, sp); } } function setHighlight() { let s = window.getSelection().toString(); if (s.length && words.findIndex(i => i == s) == -1) { words.push(s); doHightlight(highlight, s); } } function doHightlight(node,word) { var childNodes = node.childNodes,cNode; for (var i = 0; i < childNodes.length; i++) { cNode = childNodes[i]; if (cNode.nodeType == 3) {//文本节点执行高亮操作 if (cNode.parentNode.tagName == 'SPAN' && cNode.parentNode.className == 'highlight') continue;//高亮过的退出 var span = document.createElement('span'); span.className = highlight; span.innerHTML = cNode.data.replace(new RegExp('(' + word + ')', 'gi'), '<span class=highlight>$1</span>'); cNode.parentNode.replaceChild(span, cNode);/* cNode.parentNode.insertBefore(span,cNode); cNode.parentNode.removeChild(cNode);*/ } else doHightlight(cNode, word); } } function startHightlight() { if (words.length) { for (let word of words) doHightlight(highlight, word); } } //初始化 let highlight = document.querySelector('#highlight'); let words = localStorage.getItem('words'); words = words ? JSON.parse(words) : []; //startHightlight();//刷新页面不需要自动高亮去掉这句代码 </script>评论 打赏 举报解决 3无用