Complete the search function in the html page

Complete the search function in the html page

Recently I've been working on a framework that has been modified by many people. I feel dizzy from looking at the code every day, but I feel that I have made great progress. I made a backend that can configure the frontend to view different data ranges of two libraries. I am quite satisfied with it, so I shared it the other day. Today I will talk about a function I made in the past few days, which is the search function of HTML pages.

This function is mainly to input characters in the search box and then press the previous or next button at the back. The matching characters in the search area will be automatically marked with a special style. You can then continue to press the previous or next button to browse the matching characters in order, and use another style to distinguish the current matching characters from other matching characters.

The front-end display looks like this:

The html is like this:

 <div class="container" style="z-index: 999" id="searchDiv">
        <div class="keyword-search">
            Search for:
            <input id="key" type="text" style="width: 200px;" placeholder="Keyword" />
            <a href="javascript:void(0);" class="prev" onclick='wordSearch(1)'><i class="c-icon"></i></a>
            <a href="javascript:void(0);" class="next" onclick='wordSearch()'><i class="c-icon"></i></a>
        </div>
    </div>

Script code:

  <script>//Search function var oldKey0 = "";
        var index0 = -1;var oldCount0 = 0;
        var newflag = 0;
        var currentLength = 0;
        function wordSearch(flg) {
            var key = $("#key").val(); //Get key valueif (!key) {
                return; //Exit if key is empty}
            getArray();
            focusNext(flg);
        }
        function focusNext(flg) {
            if (newflag == 0) {//If new search, index is cleared index0 = 0;
            }
            if (!flg) {
                if (oldCount0 != 0) {//If there is still searching if (index0 < oldCount0) {//If the left side is not finished, go to the left focusMove(index0);
                        index0++;
                    } else if (index0 == oldCount0) {//All done index0 = 0;
                        focusMove(index0);
                        index0++;
                    }
                    else {
                        index0 = 0; //Not confirmed focusMove(index0);
                        index0++;
                    }
                }
            } else {
                if (oldCount0 != 0) {//If there is still searching if (index0 <= oldCount0 && index0 > 0) {//If the left side is not finished, go to the left index0--;
                        focusMove(index0);
                    } else if (index0 == 0) {//All done index0 = oldCount0;
                        index0--
                        focusMove(index0);
                    }
                }
            }
        }
        function getArray() {
            newflag = 1;
            $(".contrast .result").removeClass("res");
            var key = $("#key").val(); //Get key valueif (!key) {
                oldKey0 = "";
                return; //Exit if key is empty}
            if (oldKey0 != key || $(".current").length != currentLength) {
                //Reset index0 = 0;
                var index = 0;
                $(".contrast .result").each(function () {
                    $(this).replaceWith($(this).html());
                });
                pos0 = new Array();
                if ($(".contrast-wrap").hasClass("current")) {
                    currentLength = $(".current").length;
                    $(".current .contrast").each(function () {
                        $(this).html($(this).html().replace(new RegExp(key, "gm"), "<span id='result" + (index++) + "' class='result'>" + key + "</span>")); // replace });
                } else {
                    $(".contrast-wrap").addClass('current');
                    currentLength = $(".current").length;
                    $(".contrast").each(function () {
                        $(this).html($(this).html().replace(new RegExp(key, "gm"), "<span id='result" + (index++) + "' class='result'>" + key + "</span>")); // replace });
                }
                //$("#key").val(key);
                oldKey0 = key;
                //$(".contrast .result").each(function () {
                // $(this).parents('.contrast-wrap').addClass('current');
                // pos0.push($(this).offset().top);
                //});
                // pos0.push($(".contrast .result:eq(2)").offset().top - $(".contrast .result:eq(2)").parents(".contrast").offset().top);
                oldCount0 = $(".contrast .result").length;
                newflag = 0;
            }
        }
        function focusMove(index0) {
            $(".contrast .result:eq(" + index0 + ")").parents('.contrast-wrap').addClass('current');
            $(".contrast .result:eq(" + index0 + ")").addClass("res");
            var top = $(".contrast .result:eq(" + index0 + ")").offset().top + $(".contrast .result:eq(" + index0 + ")").parents(".contrast").scrollTop();
            var intop = top - $(".contrast .result:eq(" + index0 + ")").parents(".contrast").offset().top;
            $(".contrast .result:eq(" + index0 + ")").parents(".contrast").animate({ scrollTop: intop }, 200);
            if ($(".contrast .result:eq(" + index0 + ")").parents(".contrast").scrollTop() == 0) {
                $("html, body").animate({ scrollTop: top - 200 }, 200);
            } else {
                $("html, body").animate({ scrollTop: $(".contrast .result:eq(" + index0 + ")").parents(".contrast").offset().top - 200 }, 200);
            }
        }
        $('#key').change(function () {
            if ($('#key').val() == "") {
                index0 = 0;
                $(".contrast .result").each(function () {
                    $(this).replaceWith($(this).html());
                });
                oldKey0 = "";
            }
        });
    </script>

Next, let’s remember the implementation principle:

First, clear the results of the previous query. Then, according to the value of key, use regular expressions to add special styles to all matching characters in the area. For example, a span tag with a class name of result is added to the method. The odKey0 variable is used to record the value of key (next time, compare first. If they are the same, it means you want to see the next or previous content, and you don’t need to enter and match with regular expressions), oldCount0 records the total number of queries, and newflag is set to 0 (if it is not the first query, newflag is 1).

Then enter the getNext method. flg indicates whether the user pressed the previous or next button. Index0 is used to record which matching character is currently being viewed. It is compared with oldCount0 to determine whether to increase or decrease or set to 0 (if it is greater than oldCount0 or less than 0, start over).

The focusMove method is used to position the page to the current element.

jQuery methods learned:

eq() selector: The selector selects the element with the specified index value. For example: $(".contrast .result:eq(1)") selects the second element with class name result in the element with class name contrast.

parents() method: all parent elements of an element. $("p").parents('.contrast-wrap') , all elements of the p element with the class name contrast-wrap.

replace() method: replace the selected element with the specified HTML content. Note that the elements of the selected element are also replaced.

offset() method: Returns or sets the offset (position) of the matched elements relative to the document.

scrollTop() method: returns or sets the vertical position of the scroll bar of the matched elements.

Summarize

The above is the editor's introduction to the search function in HTML pages. I hope it will be helpful to everyone. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!

<<:  MySQL uses the Partition function to implement horizontal partitioning strategy

>>:  CSS World--Code Practice: Image Alt Information Presentation

Recommend

jquery+springboot realizes file upload function

This article example shares the specific code of ...

A simple method to implement scheduled backup of MySQL database in Linux

Here are the detailed steps: 1. Check the disk sp...

The final solution to Chrome's minimum font size limit of 12px

I believe that many users who make websites will ...

MySQL query optimization using custom variables

Table of contents Optimizing sorting queries Avoi...

Install OpenSSL on Windows and use OpenSSL to generate public and private keys

1. OpenSSL official website Official download add...

CSS to achieve zoom in and out close button (example code)

This effect is most common on our browser page. L...

Summary of js execution context and scope

Table of contents Preface text 1. Concepts relate...

Design a data collector with vue

Table of contents Scenario Core Issues Status mon...

HTML Grammar Encyclopedia_HTML Language Grammar Encyclopedia (Must Read)

Volume Label, Property Name, Description 002 <...

How to implement DIV's blur function

Use anti-shake to make DIV disappear when the mou...

Detailed explanation of the properties and functions of Vuex

Table of contents What is Vuex? Five properties o...

A brief discussion on macrotasks and microtasks in js

Table of contents 1. About JavaScript 2. JavaScri...

JavaScript plugin encapsulation for table switching

This article shares the encapsulation code of Jav...