Search and scroll to word on page

2019-09-01 08:33发布

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!

2条回答
姐就是有狂的资本
2楼-- · 2019-09-01 09:14

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

查看更多
Animai°情兽
3楼-- · 2019-09-01 09:20

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.

查看更多
登录 后发表回答