search
HomeWeb Front-endHTML TutorialImplement search function in html page using js
Implement search function in html page using jsNov 27, 2017 am 09:43 AM
htmljavascriptFunction

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>

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>

##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
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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software