jquery implements web page search function
This article mainly introduces the jquery implementation of the web page search function, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
When you need to find a keyword on the page Firstly, it can be realized through the search function of the browser, and secondly, it can be accurately searched and positioned through the front-end script. This article introduces the function of searching and positioning the page content through jQuery, and can expand the display of relevant information after searching
This article takes the search for the station name as an example, imitating the effect of the 12306 official website to find the station ticket time page. When the user enters a keyword and clicks the search button or presses the Enter key, jQuery matches the content through regular rules, accurately matches the keyword, and quickly positions the page Scroll to the first matching position and display relevant information (in this example, the additional information is the station's ticket start time).
HTML
The page needs to place an input box to enter the keywords to be searched, and a search button, and then the main content #content, which contains n
, that is, the name of the station that sells tickets in each time period.
<p id="search_box"> <input class="textbox" id="searchstr" type="text" size="10" name="searchstr" /> <input class="sbttn" id="search_btn" type="button" value="页内查找" /> </p> <p id="content"> <p><strong>8:00 起售车站</strong><br /> 安阳、白城、北京西、成都东、大庆、大庆西、东莞、东莞东、惠州、金华南、缙云、九江、兰州、丽水、临汾、南充、 齐齐哈尔、青田、日照、山海关、汕头、松原、温州、乌兰浩特、乌鲁木齐、武昌、武义、西安、永康、运城。</p> ....此处省略n个p </p>
CSS
Simple CSS settings for page content, where .highlight and #tip are used to set search result highlighting and information tips respectively. We will introduce the style effect of box display later.
#search_box { background: white; opacity: 0.8; text-align:right } #search_btn { background: #0f79be; margin-top: 6px; border-radius: 2px; border: 0px; width: 100px; line-height: 24px; color: white; } #searchstr { font-size: 14px; height: 20px; } .highlight { background: yellow; color: red; } #tip { background: #ffc; border: 1px solid #999; width: 110px; text-align: center; display: none; font-size: 12px; }
jQuery
First of all, we need to achieve a fixed p effect, that is, when the page is pulled down and scrolled, the input box and button used for search are always fixed at at the very top of the page for easy search.
(function($) { $.fn.fixp = function(options) { var defaultVal = { top: 10 }; var obj = $.extend(defaultVal, options); $this = this; var _top = $this.offset().top; var _left = $this.offset().left; $(window).scroll(function() { var _currentTop = $this.offset().top; var _scrollTop = $(document).scrollTop(); if (_scrollTop > _top) { $this.offset({ top: _scrollTop + obj.top, left: _left }); } else { $this.offset({ top: _top, left: _left }); } }); return $this; }; })(jQuery);
Next, we call fixp().
$(function(){ $("#search_box").fixp({ top: 0 }); });
Next, the most critical thing is to implement the search function. After entering the keyword, click the search button or press the Enter key to call the search function highlight().
$(function(){ ... $('#search_btn').click(highlight);//点击search时,执行highlight函数; $('#searchstr').keydown(function (e) { var key = e.which; if (key == 13) highlight(); }) ... });
There are many things that need to be done in the function highlight(), 1. Clear the last highlighted content, 2. Hide and clear the prompt information, 3. Determine if the input content is empty, 4. Get the input Keywords, and regular matching with the page content, and use the flag mark to find the results, and highlight the search results. 5. According to the number of search results, determine the content and position offset of the prompt information, accurately locate and display the prompt information . Please see the specific code:
$(function(){ ... var i = 0; var sCurText; function highlight(){ clearSelection();//先清空一下上次高亮显示的内容; var flag = 0; var bStart = true; $('#tip').text(''); $('#tip').hide(); var searchText = $('#searchstr').val(); var _searchTop = $('#searchstr').offset().top+30; var _searchLeft = $('#searchstr').offset().left; if($.trim(searchText)==""){ showTips("请输入查找车站名",_searchTop,3,_searchLeft); return; } //查找匹配 var searchText = $('#searchstr').val();//获取你输入的关键字; var regExp = new RegExp(searchText, 'g');//创建正则表达式,g表示全局的,如果不用g, //则查找到第一个就不会继续向下查找了; var content = $("#content").text(); if (!regExp.test(content)) { showTips("没有找到要查找的车站",_searchTop,3,_searchLeft); return; } else { if (sCurText != searchText) { i = 0; sCurText = searchText; } } //高亮显示 $('p').each(function(){ var html = $(this).html(); //将找到的关键字替换,加上highlight属性; var newHtml = html.replace(regExp, '<span class="highlight">'+searchText+'</span>'); $(this).html(newHtml);//更新; flag = 1; }); //定位并提示信息 if (flag == 1) { if ($(".highlight").size() > 1) { var _top = $(".highlight").eq(i).offset().top+$(".highlight").eq(i).height(); var _tip = $(".highlight").eq(i).parent().find("strong").text(); if(_tip=="") _tip = $(".highlight").eq(i).parent().parent().find("strong").text(); var _left = $(".highlight").eq(i).offset().left; var _tipWidth = $("#tip").width(); if (_left > $(document).width() - _tipWidth) { _left = _left - _tipWidth; } $("#tip").html(_tip).show(); $("#tip").offset({ top: _top, left: _left }); $("#search_btn").val("查找下一个"); }else{ var _top = $(".highlight").offset().top+$(".highlight").height(); var _tip = $(".highlight").parent().find("strong").text(); var _left = $(".highlight").offset().left; $('#tip').show(); $("#tip").html(_tip).offset({ top: _top, left: _left }); } $("html, body").animate({ scrollTop: _top - 50 }); i++; if (i > $(".highlight").size() - 1) { i = 0; } } } ... });
The clearSelection() function mentioned in the above code is used to clear the highlight effect. The code is as follows:
function clearSelection(){ $('p').each(function(){ //找到所有highlight属性的元素; $(this).find('.highlight').each(function(){ $(this).replaceWith($(this).html());//将他们的属性去掉; }); }); }
Finally add the showTips() function, which uses To display the search result prompt information after entering the search keyword.
$(function(){ var tipsp = '<p class="tipsClass"></p>'; $( 'body' ).append( tipsp ); function showTips( tips, height, time,left ){ var windowWidth = document.documentElement.clientWidth; $('.tipsClass').text(tips); $( 'p.tipsClass' ).css({ 'top' : height + 'px', 'left' :left + 'px', 'position' : 'absolute', 'padding' : '8px 6px', 'background': '#000000', 'font-size' : 14 + 'px', 'font-weight': 900, 'margin' : '0 auto', 'text-align': 'center', 'width' : 'auto', 'color' : '#fff', 'border-radius':'2px', 'opacity' : '0.8' , 'box-shadow':'0px 0px 10px #000', '-moz-box-shadow':'0px 0px 10px #000', '-webkit-box-shadow':'0px 0px 10px #000' }).show(); setTimeout( function(){$( 'p.tipsClass' ).fadeOut();}, ( time * 1000 ) ); } });
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
JQuery The effect plug-in for automatic carousel of pictures and texts
The above is the detailed content of jquery implements web page search function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to send web pages to the desktop as a shortcut in Edge browser? Many of our users want to display frequently used web pages on the desktop as shortcuts for the convenience of directly opening access pages, but they don’t know how to do it. In response to this problem, the editor of this issue will share the solution with the majority of users. , let’s take a look at the content shared in today’s software tutorial. The shortcut method of sending web pages to the desktop in Edge browser: 1. Open the software and click the "..." button on the page. 2. Select "Install this site as an application" in "Application" from the drop-down menu option. 3. Finally, click it in the pop-up window

Using JavaScript to develop a web voting system Abstract: With the rapid development of the Internet, online voting has become a convenient and fast way to collect public opinions and make decisions. This article will introduce the use of JavaScript to develop a simple web voting system, which enables users to select options and submit votes. Introduction: A web voting system is a program that displays multiple options on a web page and allows users to choose. It can be used in many scenarios, such as election voting, product surveys, opinion collection, etc. This article

The reasons why the web page cannot be opened are: 1. The local connection of the computer is disabled; 2. The dial-up Internet account and password are entered incorrectly; 3. There is a router failure or a problem with the router settings; 4. IE cannot open the web page due to DNS errors. ; 5. IE cannot open the web page because the hosts file is modified; 6. IE cannot open the web page because the IP address is set incorrectly or fails to be obtained.

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

To set the automatic refresh of a web page, you can use the HTML "meta" tag, the JavaScript "setTimeout" function, the "setInterval" function or the HTTP "Refresh" header. Detailed introduction: 1. Use the "meta" tag of HTML. In the "<head>" tag of the HTML document, you can use the "meta" tag to set the automatic refresh of the web page; 2. The "setTimeout" function of JavaScript, etc.

Solutions to inaccessible web pages include checking the network connection, clearing the browser cache, checking the web page address, trying to use other browsers, checking the server status, checking the domain name resolution, checking the firewall and security settings and contacting the website administrator. Detailed introduction: 1. Check the network connection to ensure that the network connection is normal. You can try to open other web pages or use other devices to access to determine whether it is a network connection problem. If other web pages can be accessed normally, it may be a problem with the web page; 2. Clear the browser cache. The browser cache may cause the web page to fail to load, etc.

The browser cannot open the web page but the network is normal. There are many possible reasons. When this problem occurs, we need to investigate step by step to determine the specific cause and solve the problem. First, determine whether the webpage cannot be opened is limited to a specific browser or whether all browsers cannot open the webpage. If only one browser cannot open the web page, you can try to use other browsers, such as Google Chrome, Firefox, etc., for testing. If other browsers are able to open the page correctly, the problem is most likely with that specific browser, possibly

How to solve the problem of web pages not opening With the rapid development of the Internet, people increasingly rely on the Internet to obtain information, communicate and entertain. However, sometimes we encounter the problem that the web page cannot be opened, which brings us a lot of trouble. This article will introduce you to some common methods to help solve the problem of web pages not opening. First, we need to determine why the web page cannot be opened. Possible reasons include network problems, server problems, browser settings problems, etc. Here are some solutions: Check network connection: First, we need
