(通用0bug)纯原生实现一个类似浏览器搜索功能(ctrl + f)

news/2023/11/28 17:53:44

如果可以实现记得点赞分享,谢谢老铁~

一、问题的描述

由于公司业务需要在搜索框中,模拟Ctrl + F 的搜索功能,支持自选可搜索区域范围,且支持回车查看下一个,上下查看,自动滚动定位,帮助小白解决不会快捷键操作的搜索。

二、问题的解决方案

首先查看浏览器自带的api啥的,抱歉,没有,找不到~
后面基于一个网站,具体参考网址是:
链接: https://www.seabreezecomputers.com/tips/find5.htm

进行了二次封装。

三、先看下原来网站的效果

将原网站下载下来的脚本命名为find5.js
直接引入,即可得到下面的搜索框效果

<script type="text/javascript" language="JavaScript" src="find5.js">
</script>

在这里插入图片描述
非常感谢此网站的作者,让我看到了曙光,因为网上其他搜索组件各种奇形怪状的bug让我倍感难受。

四、接下来就是基于原网站二次封装的脚本(重要)

因为纯原生,所以支持各种框架(vue/react)等。 不用细看下面整个脚本,直接复制粘贴创建一个新的 new_find5.js 即可

/* Cool Javascript Find on this Page
Ver 5.3
Written by Jeff Baker on September, 8, 2007.
Copyright 2014 by Jeff Baker -
Version 5.0 created 7/16/2014
Updated 8/5/2019 ver 5.4d
http://www.seabreezecomputers.com/tips/find.htm
Paste the following javascript call in your HTML web page where
you want a button called "Find on this Page...":<script type="text/javascript" language="JavaScript"
src="find5.js">
</script>*//* You may edit the following variables */
var find_text_color = "black"; // the color of the text in window
//var find_window_height = 85; // height of window - Version 5.3f - No Longer Using
/* Do not edit the variables below this line */
var find_text_inter_span = "/"; // 找出文字个数的中间连接符// Simple drag object to hold all the variables for dragging
var drag = {mousex: 0,mousey: 0,tempx: "",tempy: "",isdrag: false,drag_obj: null,drag_obj_x: 0,drag_obj_y: 0,
};var find_timer = 0; // used for timer to move window in IE when scrolling// Create highlights array to hold each new span element
var highlights = [];// Which find are we currently highlighting
var find_pointer = -1;var find_text = ""; // Global variable of searched for textvar found_highlight_rule = 0; // whether there is a highlight css rule
var found_selected_rule = 0; // whether there is a selected css ruledocument.onmousedown = MouseDown;
document.onmousemove = MouseMove;
document.onmouseup = MouseUp;document.ontouchstart = MouseDown;
document.ontouchmove = MouseMove;
document.ontouchend = MouseUp;function highlight(word, node) {if (!node) node = document.body;//var re = new RegExp(word, "i"); // regular expression of the search term // Ver 5.3c - Not using regular expressions search nowfor (node = node.firstChild; node; node = node.nextSibling) {//console.log(node.nodeName);if (node.nodeType == 3) {// text nodevar n = node;//console.log(n.nodeValue);var match_pos = 0;//for (match_pos; match_pos > -1; n=after){//match_pos = n.nodeValue.search(re); // Ver 5.3b - Now NOT using regular expression because couldn't search for $ or ^match_pos = n.nodeValue.toLowerCase().indexOf(word.toLowerCase()); // Ver 5.3b - Using toLowerCase().indexOf insteadif (match_pos > -1) {// if we found a matchvar before = n.nodeValue.substr(0, match_pos); // split into a part before the matchvar middle = n.nodeValue.substr(match_pos, word.length); // the matched word to preserve case//var after = n.splitText(match_pos+word.length);var after = document.createTextNode(n.nodeValue.substr(match_pos + word.length)); // and the part after the matchvar highlight_span = document.createElement("span"); // create a span in the middleif (found_highlight_rule == 1) {highlight_span.className = "highlight";} else {highlight_span.style.backgroundColor = "yellow";highlight_span.style.color = "black";}highlight_span.appendChild(document.createTextNode(middle)); // insert word as textNode in new spann.nodeValue = before; // Turn node data into beforen.parentNode.insertBefore(after, n.nextSibling); // insert aftern.parentNode.insertBefore(highlight_span, n.nextSibling); // insert new spanhighlights.push(highlight_span); // add new span to highlights arrayhighlight_span.id = "highlight_span" + highlights.length;node = node.nextSibling; // Advance to next node or we get stuck in a loop because we created a span (child)}}} // if not text node then it must be another elementelse {// nodeType 1 = element   原 matcher = /textarea|input/i   让input不支持搜索,现在把input从正则中去除,这个是定制化需求,看个人需要来改if (node.nodeType == 1 &&node.nodeName.match(/textarea/i) &&node.type.match(/textarea|text|number|search|email|url|tel/i) &&!getStyle(node, "display").match(/none/i))textarea2pre(node);else {if (node.nodeType == 1 &&!getStyle(node, "visibility").match(/hidden/i))if (node.nodeType == 1 && !getStyle(node, "display").match(/none/i))// Dont search in hidden elements// Dont search in display:none elementshighlight(word, node);}}}
} // end function highlight(word, node)function unhighlight() {for (var i = 0; i < highlights.length; i++) {var the_text_node = highlights[i].firstChild; // firstChild is the textnode in the highlighted spanvar parent_node = highlights[i].parentNode; // the parent element of the highlighted span// First replace each span with its text node nodeValueif (highlights[i].parentNode) {highlights[i].parentNode.replaceChild(the_text_node, highlights[i]);if (i == find_pointer) selectElementContents(the_text_node); // ver 5.1 - 10/17/2014 - select current findparent_node.normalize(); // The normalize() method removes empty Text nodes, and joins adjacent Text nodes in an elementnormalize(parent_node); // Ver 5.2 - 3/10/2015 - normalize() is incorrect in IE. It will combine text nodes but may leave empty text nodes. So added normalize(node) function below}}// Now reset highlights arrayhighlights = [];find_pointer = -1; // ver 5.1 - 10/17/2014
} // end function unhighlight()function normalize(node) {//http://stackoverflow.com/questions/22337498/why-does-ie11-handle-node-normalize-incorrectly-for-the-minus-symbolif (!node) {return;}if (node.nodeType == 3) {while (node.nextSibling && node.nextSibling.nodeType == 3) {node.nodeValue += node.nextSibling.nodeValue;node.parentNode.removeChild(node.nextSibling);}} else {normalize(node.firstChild);}normalize(node.nextSibling);
}function findit(root) {// put the value of the textbox in stringvar string = document.getElementById("fwtext").value;// 8-9-2010 Turn DIV to hidden just while searching so doesn't find the text in the windowfindwindow.style.visibility = "hidden";//findwindow.style.display = 'none';// if the text has not been changed and we have previous findsif (find_text.toLowerCase() ==document.getElementById("fwtext").value.toLowerCase() &&find_pointer >= 0) {findnext(); // Find the next occurrence} else {unhighlight(); // Remove highlights of any previous findsif (string == "") {// if empty stringfind_msg.innerHTML = "";total.innerHTML = 0;document.getElementById("closeIcon").style.display = "none";findwindow.style.visibility = "visible";return;}find_text = string;// Ver 5.0a - 7/18/2014. Next four lines because root node won't exist until doc loadsif (root != null) var node = document.getElementById(root);else var node = null;highlight(string, node); // highlight all occurrences of search stringif (highlights.length > 0) {// if we found occurencesfind_pointer = -1;findnext(); // Find first occurrence} else {find_msg.innerHTML = " <b>0 " + find_text_inter_span + " 0</b>"; // ver 5.1 - 10/17/2014 - changed from "Not Found"find_pointer = -1;total.innerHTML = 0;}}findwindow.style.visibility = "visible";//findwindow.style.display = 'block';
} // end function findit()function findnext() {var current_find;if (find_pointer != -1) {// if not first findcurrent_find = highlights[find_pointer];// Turn current find back to yellowif (found_highlight_rule == 1) {current_find.className = "highlight";} else {current_find.style.backgroundColor = "yellow";current_find.style.color = "black";}}find_pointer++;if (find_pointer >= highlights.length)// if we reached the endfind_pointer = 0; // go back to first findvar display_find = find_pointer + 1;find_msg.innerHTML =display_find + "" + find_text_inter_span + "" + highlights.length;total.innerHTML = highlights.length;current_find = highlights[find_pointer];// Turn selected find orange or add .find_selected css class to itif (found_selected_rule == 1) {current_find.className = "find_selected";} else {current_find.style.backgroundColor = "orange";current_find.style.color = "black";}//highlights[find_pointer].scrollIntoView(); // Scroll to selected elementscrollToPosition(highlights[find_pointer]);
} // end findnext()// This function is to find backwards by pressing the Prev button
function findprev() {var current_find;if (highlights.length < 1) {return;}if (find_pointer != -1) {// if not first findcurrent_find = highlights[find_pointer];// Turn current find back to yellowif (found_highlight_rule == 1) {current_find.className = "highlight";} else {current_find.style.backgroundColor = "yellow";current_find.style.color = "black";}}find_pointer--;if (find_pointer < 0)// if we reached the beginningfind_pointer = highlights.length - 1; // go back to last findvar display_find = find_pointer + 1;find_msg.innerHTML =display_find + "" + find_text_inter_span + "" + highlights.length;total.innerHTML = highlights.length;current_find = highlights[find_pointer];// Turn selected find orange or add .find_selected css class to itif (found_selected_rule == 1) {current_find.className = "find_selected";} else {current_find.style.backgroundColor = "orange";current_find.style.color = "black";}//highlights[find_pointer].scrollIntoView(); // Scroll to selected elementscrollToPosition(highlights[find_pointer]);
} // end findprev()// This function resets the txt selection pointer to the
// beginning of the body so that we can search from the
// beginning for the new search string when somebody
// enters new text in the find boxfunction MouseDown(event) {drag.tempx = drag.tempy = ""; // For single click on objectif (!event) event = window.event; // 10/5/2014 - ver 5.0d - for older IE <= 9var fobj = event.target || event.srcElement; // The element being clicked on (FF || IE)// get current screen scrollTop and ScrollLeftvar scrollLeft =document.body.scrollLeft || document.documentElement.scrollLeft;var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;// ver 5.1 - 10/17/2014 - Let users highlight textareas and inputs by not dragging themif (typeof fobj.nodeName != "undefined")if (fobj.nodeName.toLowerCase() == "input" ||fobj.nodeName.toLowerCase() == "textarea")return true;// If parent or grandparents of obj is a dragme item then make the parent the fobjfor (fobj; fobj; fobj = fobj.parentNode) {// 7/30/2014 ver 5.0bif (fobj.className) if (String(fobj.className).match(/dragme/i)) break;}if (fobj)if (fobj.className.match(/dragme/i)) {drag.isdrag = true; // Tell mouseMove we are draggingdrag.drag_obj = fobj; // Put dragged element into global variabledrag.drag_obj_x = parseInt(drag.drag_obj.offsetLeft); // get current x of elementdrag.drag_obj_y = parseInt(drag.drag_obj.offsetTop); // get current y of element// Add scrollTop and scrollLeft to recorded mouse positiondrag.mousex = event.clientX + scrollLeft;drag.mousey = event.clientY + scrollTop;/* if touchevents from iphone */if (event.type == "touchstart")if (event.touches.length == 1) {// Only deal with one fingervar touch = event.touches[0]; // Get the information for finger #1// node.style.position = "absolute";drag.mousex = touch.pageX; // includes scroll offsetdrag.mousey = touch.pageY; // includes scroll offset}return true; // 8/25/2014 version 5.0c (Now all buttons and onclick work on iphone and android)}
} // end function MouseDown(event)function MouseMove(event) {if (drag.isdrag) {// Use 'event' above because IE only uses event and FF can use anythingif (!event) event = window.event; // 10/5/2014 - ver 5.0d - for older IE <= 9drag.tempx = event.clientX; // record new mouse position xdrag.tempy = event.clientY; // record new mouse position y// get current screen scrollTop and ScrollLeftvar scrollLeft =document.body.scrollLeft || document.documentElement.scrollLeft;var scrollTop =document.body.scrollTop || document.documentElement.scrollTop;// Add scrollTop and scrollLeft to drag.tempx and drag.tempydrag.tempx += scrollLeft;drag.tempy += scrollTop;drag.drag_obj.style.position = "absolute";/* if touchevents from iphone */if (event.type == "touchmove")if (event.touches.length == 1) {// Only deal with one fingervar touch = event.touches[0]; // Get the information for finger #1drag.tempx = touch.pageX; // includes scroll offsetdrag.tempy = touch.pageY; // includes scroll offset}drag.drag_obj.style.left =drag.drag_obj_x + drag.tempx - drag.mousex + "px"; // 7/30/2014 ver 5.0bdrag.drag_obj.style.top = drag.drag_obj_y + drag.tempy - drag.mousey + "px"; // 7/30/2014 ver 5.0breturn false;}
} // end function MouseMove(event)function MouseUp() {if (drag.isdrag == true) {if (drag.tempx == "" && drag.tempy == "") {//if (document.getElementById('find_msg'))// document.getElementById('find_msg').innerHTML += " You clicked!";}}drag.isdrag = false;
}function isOnScreen(el) {// Version 5.4d/* This checks to see if an element is within the current user viewport or not */var scrollLeft =document.body.scrollLeft || document.documentElement.scrollLeft;var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;var screenHeight =window.innerHeight ||document.documentElement.clientHeight ||document.body.clientHeight; // Version 1.2.0var screenWidth =window.innerWidth ||document.documentElement.clientWidth ||document.body.clientWidth; // Version 1.2.0/* New way: el.getBoundingClientRect always returnsleft, top, right, bottom ofan element relative to the current screen viewport */var rect = el.getBoundingClientRect();if (rect.bottom >= 0 &&rect.right >= 0 &&rect.top <= screenHeight &&rect.left <= screenWidth)// Version 1.2.0 - Changed from scrollBottom and scrollRightreturn true;else {// Verison 1.0.2 - Calculate how many pixels it is offscreenvar distance = Math.min(Math.abs(rect.bottom),Math.abs(rect.right),Math.abs(rect.top - screenHeight),Math.abs(rect.left - screenWidth));return -Math.abs(distance); // Version 1.0.2 - Return distance as a negative. Used to return false if off screen}
}function scrollToPosition(field) {// This function scrolls to the DIV called 'edited'// It is called with onload.  'edited' only exists if// they just edited a comment or the last comment// if they just sent a commentvar scrollLeft =document.body.scrollLeft || document.documentElement.scrollLeft;var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;if (field) {if (isOnScreen(field) != true) {// Version 5.4dvar isSmoothScrollSupported ="scrollBehavior" in document.documentElement.style;if (isSmoothScrollSupported) {field.scrollIntoView({behavior: "smooth",block: "center",});} else {field.scrollIntoView(false);}}}
}/* It is not possible to get certain styles set in css such as display using
the normal javascript.  So we have to use this function taken from:
http://www.quirksmode.org/dom/getstyles.html */
function getStyle(el, styleProp) {// if el is a string of the id or the actual object of the elementvar x = document.getElementById(el) ? document.getElementById(el) : el;if (x.currentStyle)// IEvar y = x.currentStyle[styleProp];else if (window.getComputedStyle)// FFvar y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);return y;
}function create_div_html(isShowTxt, root) {console.log("enter this method create_div_html");if (document.documentElement.scrollTop)var current_top = document.documentElement.scrollTop;else var current_top = document.body.scrollTop;if (document.getElementById("findwindow")) {console.log("have find findwindow");findwindow = document.getElementById("findwindow");} else {findwindow.id = "findwindow";findwindow.style.position = "absolute";document.body.appendChild(findwindow);document.body.insertBefore(findwindow, document.body.firstChild);findwindow.className = "findwindow dragme";findwindow.style.visibility = "hidden";}findwindow.style.display = "flex";findwindow.style.alignItems = "center";findwindow.style.justifyContent = "space-around";findwindow.style.flexWrap = "wrap";findwindow.style.color = find_text_color;findwindow.style.padding = "0px";findwindow.style.fontSize = "14px";findwindow.className = "outMain";var string = "";var searchIcon ='<div id="searchIcon" style="display: flex;align-items: center;justify-content: center;cursor: pointer;width: 30px;cursor: pointer;"><svg focusable="false" class="" data-icon="search" width="1em" height="1em" fill="#6C6C6C" aria-hidden="true" viewBox="64 64 896 896"><path d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0011.6 0l43.6-43.5a8.2 8.2 0 000-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z"></path></svg></div>';var closeIcon ='<div id="closeIcon" style="display: none;align-items: center;cursor: pointer;"><svg focusable="false" class="" data-icon="close-circle" width="1em" height="1em" fill="#E3E6ED" aria-hidden="true" viewBox="64 64 896 896"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-.3L512 563.4l-99.3 118.4-66.1.3c-4.4 0-8-3.5-8-8 0-1.9.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 01-1.9-5.2c0-4.4 3.6-8 8-8l66.1.3L512 464.6l99.3-118.4 66-.3c4.4 0 8 3.5 8 8 0 1.9-.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z"></path></svg></div>';string +='<div id="look" style="color: #363636">查找:</div>' +'<div id="window_body" style="padding-left: 15px;height: 40px;border: 1px solid #DCDFE6;border-radius: 5px;">' +'<form οnsubmit="return false;"><div style="display: flex;padding: 3px;"><input autocomplete="off" type="search" ' +' class="paperview-input-text" ' +' style="float:left;height: 30px;width: 100%;margin-left: -18px;border: none;outline: 0px;" id="fwtext"' +' placeholder="从文本中查询关键词"/>' +closeIcon +searchIcon +"</div>";string +="</form></div>" +'<div class="searchRight" style=" display: flex;">' +'<div class="res"  style=" display: flex;justify-content: space-around;align-items: center;">' +`<div class="txt" style="font-size: 14px; color: #6c6c6c;">结果命中:<span id="total">0</span></div>` +'<div id="btnUp" class="btn item" style="display: flex;justify-content: center;align-items: center;width: 68px;height: 24px;background: #1b4975;border-radius: 4px;font-size: 12px;color: #ffffff; margin: 12px 2px;cursor: pointer;margin-left: 10px;">上一个</div>' +'<div id="btnDown" class="btn item" style="display: flex;justify-content: center;align-items: center;width: 68px;height: 24px;background: #1b4975;border-radius: 4px;font-size: 12px;color: #ffffff; margin: 12px 2px;cursor: pointer;">下一个</div>' +'<div class="txt" id="find_msg"  style="font-size: 14px; color: #6c6c6c;margin-left: 10px;">0/0</div>' +"</div>" +"</div>";// ^zxd - 05/24/2023findwindow.innerHTML = string;// search input 实时监听文本内容变化 , 一直输入一直搜索,比onchange失去焦点搜索好一点var fwtextDom = document.getElementById("fwtext");let btnUp = document.getElementById("btnUp");let btnDown = document.getElementById("btnDown");let closeDom = document.getElementById("closeIcon");let searchDom = document.getElementById("searchIcon");let windowBody = document.getElementById("window_body");if (isShowTxt) {windowBody.style.margin = "0px 10px";}if (document.all) {// ie浏览器的监听事件console.log("onpropertychange method only for IE");fwtextDom.onpropertychange = () => {findit(root);// findit方法会如果网页中找不到search txt会失去 鼠标输入焦点,变得不可以再输入,需要设置find_pointer为一直到不到元素,才不会失去焦点find_pointer = -1;};} else {// 其他浏览器的监听事件console.log("oninput method for Chrome and other except IE");// 点击搜索searchDom.onclick = () => {findit(root);};fwtextDom.oninput = function () {// findit方法会如果网页中找不到search txt会失去 鼠标输入焦点,变得不可以再输入,需要设置find_pointer为一直到不到元素,才不会失去焦点find_pointer = -1;if (fwtextDom.value) {document.getElementById("closeIcon").style.display = "flex";}};btnUp.onclick = () => {findprev();};btnDown.onclick = () => {findit(root);};fwtextDom.onkeydown = (event) => {if (event.code === "Enter") {findit(root);}};closeDom.onclick = () => {fwtextDom.value = "";findit(root);};}// Check to see if css rules exist for hightlight and find_selected.var sheets = document.styleSheets;for (var i = 0; i < sheets.length; i++) {// IE <= 8 uses rules; FF & Chrome and IE 9+ users cssRulestry {// Version 5.4c - Fix Firefox "InvalidAccessError: A parameter or an operation is not supported by the underlying object" bugvar rules = sheets[i].rules ? sheets[i].rules : sheets[i].cssRules;if (rules != null)for (var j = 0; j < rules.length; j++) {if (rules[j].selectorText == ".highlight") found_highlight_rule = 1;else if (rules[j].selectorText == ".find_selected")found_selected_rule = 1;}} catch (error) {console.error("Caught Firefox CSS loading error: " + error);}}return string;
}function textarea2pre(el) {// el is the textarea element// If a pre has already been created for this textarea element then use itif (el.nextSibling && el.nextSibling.id && el.nextSibling.id.match(/pre_/i))var pre = el.nextsibling;else var pre = document.createElement("pre");var the_text = el.value; // All the text in the textarea// replace <>" with entitiesthe_text = the_text.replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');//var text_node = document.createTextNode(the_text); // create text node for pre with text in it//pre.appendChild(text_node); // add text_node to prepre.innerHTML = the_text;// Copy the complete HTML style from the textarea to the prevar completeStyle = "";if (typeof getComputedStyle !== "undefined") {// webkitcompleteStyle = window.getComputedStyle(el, null).cssText;if (completeStyle != "")// Verison 5.3f - Is empty in IE 10 and Firefoxpre.style.cssText = completeStyle; // Everything copies fine in Chromeelse {// Version 5.3f - Because cssText is empty in IE 10 and Firefoxvar style = window.getComputedStyle(el, null);for (var i = 0; i < style.length; i++) {completeStyle +=style[i] + ": " + style.getPropertyValue(style[i]) + "; ";}pre.style.cssText = completeStyle;}} else if (el.currentStyle) {// IEvar elStyle = el.currentStyle;for (var k in elStyle) {completeStyle += k + ":" + elStyle[k] + ";";}//pre.style.cssText = completeStyle;pre.style.border = "1px solid black"; // border not copying correctly in IE}el.parentNode.insertBefore(pre, el.nextSibling); // insert pre after textarea// If textarea blur then turn pre back on and textarea offel.onblur = function () {this.style.display = "none";pre.style.display = "block";};// If textarea changes then put new value back in preel.onchange = function () {pre.innerHTML = el.value.replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');};el.style.display = "none"; // hide textareapre.id = "pre_" + highlights.length; // Add id to pre// Set onclick to turn pre off and turn textarea back on and perform a click on the textarea// for a possible οnclick="this.select()" for the textareapre.onclick = function () {this.style.display = "none";el.style.display = "block";el.focus();el.click();};// this.parentNode.removeChild(this); // old remove pre in onclick function above
} // end function textarea2pre(el)// ver 5.1 - 10/17/2014
function selectElementContents(el) {/* http://stackoverflow.com/questions/8019534/how-can-i-use-javascript-to-select-text-in-a-pre-node-block */if (window.getSelection && document.createRange) {// IE 9 and non-IEvar range = document.createRange();range.selectNodeContents(el);var sel = window.getSelection();sel.removeAllRanges();sel.addRange(range);} else if (document.body.createTextRange) {// IE < 9var textRange = document.body.createTextRange();textRange.moveToElementText(el);textRange.select();//textRange.execCommand("Copy");}
} // end function selectElementContents(el)// This part creates a visible button on the HTML page to
// where the script is pasted in the HTML code
// document.write('<input type="button" value="Find on this page..."'
//   + ' οnclick="show();">');// Create the DIV
var findwindow = document.createElement("div");// setTimeout("initFindWin()", 5000)// 启动初始化函数,必须要在插件渲染完成之后再初始化,不然就会创建新的div函数,所以vue使用 mounted 初始化
const initFindWin = (isShowTxt, root = "body") => {debugger;create_div_html(isShowTxt, root);document.getElementById("look").style.display = isShowTxt ? "block" : "none";
};
export default initFindWin;

先看下效果 : 且支持自适应换行
在这里插入图片描述

四、最后注意几点事项

这里的第一个参数是代表是否展示label: ‘查看’,
第二个参数 是指定的区域进行搜索。默认是body 整个网页
initFindWin(false, “contentMain”);

1.先在你的模块界面里先引入脚本,然后加入容器div且指定id:findwindow
 <div id="findwindow"></div>
2.如果是纯js, 则只需要将new_find5.js 最后一行代码注释且立即执行initFindWin() 即可。
3.如果是vue, 这需要在 onMounted() 中调用,如
import initFindWin from "@/utils/new_find5.js";
export default {setup() {onMounted(() => {// 这里的第一个参数是代表是否展示label: '查看', 第二个参数 是指定的区域进行搜索。默认是body 整个网页initFindWin(false, "contentMain");});return {};},
};
4.如果是react + hooks, 则需要在 useEffect() 中调用
import initFindWin from "@/utils/new_find5.js";useEffect(() => {initFindWin(false, "contentMain");}, []);

创作不容易,请勿抄袭,欢迎转载请说明来源即可


http://www.ppmy.cn/news/170848.html

相关文章

pc端好用的txt阅读器推荐及下载地址

Koodo Reader&#xff1a;一款界面简洁&#xff0c;功能强大的pc端阅读器&#xff0c;适合阅读文献及小说&#xff0c;支持包括txt在内的多种主流格式 Koodo Reader 是一个开源免费的电子书阅读器&#xff0c;支持多达15种主流电子书格式&#xff0c; 内置笔记、高亮、翻译功能…

【2023-6-02】关于项目中数组遍历场景的记录

数组遍历的场景 先说下&#xff0c;简单的需求&#xff1a; 存在一个下拉框&#xff0c;每次选中一个选项后&#xff0c;需要展示在上方的列表中&#xff0c;且删除掉下来框中该选项删除列表中对应值时&#xff0c;需要下拉框数据中增加该值 实现思路 下拉框选中值&#xf…

用安卓手机看txt小说,哪些阅读器APP更好用?

txt是最常见的一种文档格式&#xff0c;大家经常会下载一些txt小说或资料在手机上阅读。经过多款测评&#xff0c;选出以下小说阅读器&#xff0c;体验相对较好&#xff0c;推荐给喜欢在手机上看小说的朋友们。 1&#xff09; Neat Reader 这款阅读器界面设计比较整洁&#x…

推荐一款很棒的电脑上看小说阅读器

推荐一款很棒的电脑上看小说阅读器 上班的时候想要摸鱼怎么办&#xff1f; 摸鱼推荐: 摸鱼神器 前两天摸鱼被老板抓到了&#xff0c;今天发现了一款超好用的摸鱼神器&#xff01;一款炒鸡隐秘的看小说的软件&#xff0c;亲测十分实用。 白天看晚上看&#xff0c;甚至熬夜看&…

用安卓手机看txt小说,阅读器APP怎么选

txt是最常见的一种文档格式&#xff0c;大家经常会下载一些txt小说或资料在手机上阅读。经过多款测评&#xff0c;选出以下小说阅读器&#xff0c;体验相对较好&#xff0c;推荐给喜欢在手机上看小说的朋友们。 1&#xff09; Neat Reader 这款阅读器界面设计比较整洁&#x…

安卓手机上有哪些好用的小说阅读器?

现在&#xff0c;使用手机阅读的人真的越来越多了&#xff0c;我在地铁通勤路上经常能看到有人拿着手机看小说。作为小说爱好者&#xff0c;经过多款测评&#xff0c;选出以下小说阅读器&#xff0c;体验相对较好&#xff0c;推荐给喜欢在手机上看小说的朋友们。 第一款&#…

用Windows电脑看txt小说,阅读器软件怎么选

Windows电脑上有哪些好用的TXT阅读器&#xff1f;综合来看&#xff0c;以下小说阅读器&#xff0c;体验相对较好。这些阅读器都支持TXT EPUB等常见小说格式。 Top1&#xff1a;Neat Reader Neat Reader这款阅读器整体界面都给人一种非常舒适的体验&#xff0c;操作傻瓜&#…

怎么在Windows电脑上阅读txt小说,小说阅读器推荐

txt是使用广泛的小说电子书格式&#xff0c;想必平时大家通常会遇到自己使用的小说阅读器不能在Windows系统上兼容的问题&#xff0c;因为工作的原因&#xff0c;小编接触到很多不同的阅读器&#xff0c;今天小编将为大家推荐Windows电脑上最好的3个小说阅读器。 Top1&#xf…

Windows电脑上有哪些好用的txt小说阅读器?

txt是常见的电子书格式&#xff0c;我们在网上下载小说时经常会遇到。今天小编将为大家推荐几款Windows电脑上比较好用的3个小说阅读器。 Top1&#xff1a;Neat Reader 无论从阅读器的兼容度还是从便捷性的角度上&#xff0c;这款阅读器都完成的非常优秀。整体界面都给人一种非…

安卓手机上最好的3个mobi阅读器

如epub、azw3一样&#xff0c;mobi也是一种常见的电子书格式&#xff0c;它可以用亚马逊电子设备打开阅读&#xff0c;但是在手机上应该怎么打开呢&#xff1f;其实通过一些支持mobi格式的阅读器就可以打开。今天小编就为大家推荐3个在安卓手机上可用的mobi阅读器。 第一款&am…

安卓手机上最好用的3个azw3阅读器

azw/azw3是亚马逊推出的一种电子书格式&#xff0c;它填补了Mobi对于复杂排版的缺陷&#xff0c;以及原来mobi或azw内容排版上的一些缺陷。目前从Amazon购买的书&#xff0c;大部分已经是azw3格式了&#xff0c;而以前主流的mobi格式则越来越少&#xff0c;它正逐渐取代mobi成为…

怎么在电脑上阅读txt小说,小说阅读器推荐

txt是一种使用广泛的文档、电子书格式&#xff0c;因为工作的原因&#xff0c;小编接触到很多不同的阅读器&#xff0c;今天小编将为大家推荐市面上最好的3个txt阅读器。 Top1&#xff1a;Neat Reader 这款在小编用过的阅读器中绝对排第一位&#xff0c;无论从阅读器的兼容度…

安卓手机上最好的3个azw3阅读器

azw3是亚马逊推出的一种电子书格式&#xff0c;它填补了Mobi对于复杂排版的缺陷&#xff0c;以及原来mobi或azw内容排版上的一些缺陷。目前从Amazon购买的书&#xff0c;大部分已经是azw3格式了&#xff0c;而以前主流的mobi格式则越来越少&#xff0c;它正逐渐取代mobi成为Kin…

三款超好用手机epub阅读器

三款超好用手机epub阅读器 在我们使用手机看各种格式的电子书时&#xff0c;可能会出现不能打开的状况。或者是太多电子书不能很好的整理&#xff0c;找书的时候很不方便&#xff0c;这时我们就需要一款阅读器来帮助我们解决这个问题。 epub格式是大多数人都非常喜欢的格式&a…

3款Android版epub阅读器推荐

3款Android版epub阅读器推荐 在这快节奏的生活中&#xff0c;我们常常见到地铁里的&#xff0c;马路上&#xff0c;到处都是的低头族。手机变成了我们必不可少&#xff0c;不能离身的一部分。 大部分原因还是手机的功能太强大了&#xff0c;除了联系他人&#xff0c;还可以学…

评测三款最流行的mobi阅读器(windows适用)

不知道大家常用的阅读器是什么呢&#xff1f;平常大家都是怎么打开mobi格式的呢&#xff1f;对于经常看电子书的小伙伴来说&#xff0c;mobi这种电子书格式一定是很熟悉的&#xff0c;而能姿势优美地解析mobi的阅读器软件却不算多。在这里我给大家评测3种windows上可用的mobi阅…

电脑端epub阅读器推荐

在电子阅读时代&#xff0c;墨水屏电子阅读器固然有其不可替代的优势&#xff0c;但是在我们普通人的生活工作中它的使用频率远不及电脑。虽然墨水屏的仿真感和护眼优势比较明显&#xff0c;但其实电脑阅读也可以满足大部分阅读者们的需求。选择好合适的阅读器可以使电脑也变成…

Android手机有哪学好用的epub阅读器app

小编作为一名合格的社畜&#xff0c;每天地铁单程通勤1h左右&#xff0c;为打发时间&#xff0c;经常选择安静地看电子书&#xff0c;避免刷短视频蚌埠住了&#xff0c;笑出声就真的社死了。也顺便当提高自己的吧。电子书的格式很多&#xff0c;小编接触最多就是Epub和mobi&…

安卓手机上有哪些好用的txt小说阅读器?

txt格式是一款非常常见的小说格式&#xff0c;很多手机由于自身不能直接打开txt格式文件或者软件使用感较差而给我们阅读带来困扰。今天小编就为大家介绍几款可以在安卓手机上使用的txt小说阅读器。 第一款&#xff1a;neat reader 这款阅读器界面设计相当整洁&#xff0c;色调…

评测三款免费的mobi阅读器(windows适用)

mobi作为一款电子书格式&#xff0c;其电子书资源之丰富&#xff0c;书迷们都有所体会。但它也有个弊端&#xff0c;不是什么系统都能直接打开mobi的&#xff0c;所以看mobi电子书一定需要一款趁手的阅读器。下面我下载了几款免费的mobi阅读器&#xff0c;简要评测一下&#xf…
最新文章