Home Web Front-end HTML Tutorial Implement search function in html page using js

Implement search function in html page using js

Nov 27, 2017 am 09:43 AM
html javascript Function

Today I will talk about a function that I have been working on in the past few days, which is the search function of the html page. This function is mainly implemented by entering characters in the html search box, and then pressing the previous and next buttons. The matching characters in the query area will automatically be marked with a special style, and then you can continue to press the previous button. The next button will browse the matching characters in order and use another pattern to distinguish the current matching character from other matching characters. Pay with html code!

Style demo:

Implement search function in html page using js

Code demo:

html

<div class="container" style="z-index: 999" id="searchDiv">
<div class="keyword-search">
查找:
<input id="key" type="text" style="width: 200px;" placeholder="关键词" />
<a href="javascript:void(0);" class="prev" onclick=&#39;wordSearch(1)&#39;><i class="c-icon"></i></a>
<a href="javascript:void(0);" class="next" onclick=&#39;wordSearch()&#39;><i class="c-icon"></i></a>
</div>
</div>
Copy after login

script

    <script>//搜索功能
        var oldKey0 = "";
        var index0 = -1;var oldCount0 = 0;
        var newflag = 0;
        var currentLength = 0;

        function wordSearch(flg) {
            var key = $("#key").val(); //取key值
            if (!key) {
                return; //key为空则退出
            }
            getArray();
            focusNext(flg);

        }

        function focusNext(flg) {
            if (newflag == 0) {//如果新搜索,index清零
                index0 = 0;
            }
            if (!flg) {
                if (oldCount0 != 0) {//如果还有搜索
                    if (index0 < oldCount0) {//左边如果没走完,走左边
                        focusMove(index0);
                        index0++;
                    } else if (index0 == oldCount0) {//都走完了
                        index0 = 0;
                        focusMove(index0);
                        index0++;
                    }
                    else {
                        index0 = 0;//没确定
                        focusMove(index0);
                        index0++;
                    }
                }

            } else {
                if (oldCount0 != 0) {//如果还有搜索
                    if (index0 <= oldCount0 && index0 > 0) {//左边如果没走完,走左边
                        index0--;
                        focusMove(index0);
                    } else if (index0 == 0) {//都走完了
                        index0 = oldCount0;
                        index0--
                        focusMove(index0);
                    }
                }
            }
        }
        function getArray() {
            newflag = 1;
            $(".contrast .result").removeClass("res");
            var key = $("#key").val(); //取key值
            if (!key) {
                oldKey0 = "";
                return; //key为空则退出
            }
            if (oldKey0 != key || $(".current").length != currentLength) {
                //重置
                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=&#39;result" + (index++) + "&#39; class=&#39;result&#39;>" + key + "</span>")); // 替换
                    });
                } else {
                    $(".contrast-wrap").addClass(&#39;current&#39;);
                    currentLength = $(".current").length;
                    $(".contrast").each(function () {
                        $(this).html($(this).html().replace(new RegExp(key, "gm"), "<span id=&#39;result" + (index++) + "&#39; class=&#39;result&#39;>" + key + "</span>")); // 替换
                    });
                }
                //$("#key").val(key);
                oldKey0 = key;

                //$(".contrast .result").each(function () {
                //    $(this).parents(&#39;.contrast-wrap&#39;).addClass(&#39;current&#39;);
                //    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(&#39;.contrast-wrap&#39;).addClass(&#39;current&#39;);
            $(".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);
            }

        }


        $(&#39;#key&#39;).change(function () {
            if ($(&#39;#key&#39;).val() == "") {
                index0 = 0;
                $(".contrast .result").each(function () {
                    $(this).replaceWith($(this).html());
                });
                oldKey0 = "";
            }
        });
    </script>
Copy after login

##Next, note the implementation principle:

First clear the last query results, and then use regular expressions to add a special style to all matching characters in the area based on the key value. For example, a class name is added to the method. For the span tag of result, use the odKey0 variable to record the value of the key (compare first when entering next time. If they are the same, it means you need to look at the next or previous content, so you don’t need to use regular expression matching again). oldCount0 records the total query. The number that comes out, 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. Use index0 to record which matching character is currently being viewed. Compare it with oldCount0 to determine whether it is incremented or decremented or set to 0 ( If it is greater than oldCount0 or less than 0, it will start again).

The focusMove method is an operation that positions the page to the current element.

Related recommendations:

How to implement digital focus chart carousel code in HTML

How to insert pictures in HTML

What to do if DIVs overlap each other in HTML

How to use in HTML margin 0 auto


The above is the detailed content of Implement search function in html page using js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles