Search and scroll to word on page

2019-09-01 08:34发布

问题:

My client wants to add a search box on specific pages that will allow their user to search for a product and it will scroll to that text. This way it's easier for her to direct her clients to the right part of the page.

This is easily done using Ctrl-F with the browsers search function. Unfortunately the client wants the search to be part of the site.

Any advice on how to accomplish this? I've struggled to find a wordpress plug-in and any JQuery code I've used around the internet has failed me.

Thanks kindly in advance!

回答1:

Not sure about its browser support, but you can call window.find("your query here") to use the browser's Ctrl+F functionality

More info here



回答2:

You can use jQuery's :contains selector.

$("window").scrollTop($("*:contains('search text here'):eq(n)").offset().top);

where n is the nth-match. You can probably get the number of matches first then by pressing enter or tab then scroll to the ++n-th match.