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

MySQL index usage instructions (single-column index and multi-column index)

1. Single column index Choosing which columns to ...

Detailed explanation of basic data types in mysql8.0.19

mysql basic data types Overview of common MySQL d...

Detailed explanation of Linux text processing tools

1. Count the number of users whose default shell ...

A brief analysis of the count tracking of a request in nginx

First, let me explain the application method. The...

Summary of important components of MySQL InnoDB

Innodb includes the following components 1. innod...

MySQL database aggregate query and union query operations

Table of contents 1. Insert the queried results 2...

HTML uses form tags to implement the registration page example code

Case Description: - Use tables to achieve page ef...

How to implement Mysql scheduled tasks under Linux

Assumption: The stored procedure is executed ever...

How to use JS to parse the excel content in the clipboard

Table of contents Preface 1. Paste Events and Cli...

HTML+CSS+JavaScript to achieve list loop scrolling example code

Description: Set a timer to replace the content of...

Web designer is a suitable talent

<br />There is no road in the world. When mo...

How to install Android x86 in vmware virtual machine

Sometimes you just want to test an app but don’t ...

VMWare virtual machine 15.X LAN network configuration tutorial diagram

Recently, I have been working on several virtual ...

Mysql Chinese sorting rules description

When using MySQL, we often sort and query a field...