Javascript find and scroll to text
I need a bit of Javascript that will find some text in the html page and then scroll to that point.
So something like "Are you a Lib Dem or Tory supporter and how do you feel about the deal?" would scroll down to the bottom of the page for this bbc news page: http://news.bbc.co.uk/1/hi/uk_politics/election_2010/8676607.stm
Im hoping there is a b开发者_开发技巧uilt in function for both the find text and scroll.
Try this. It works on the site you provided:
$(window).scrollTop($("*:contains('Are you a Lib Dem or Tory'):last").offset().top);
It finds last, deepest element that contains given phrase on the page and scrolls to it.
If you want to do the same thing without jQuery you need to use XPath becasue CSS didn't get contains()
selector.
window.scrollBy(0, document.evaluate("//*[text()[contains(., 'Lib Dem')]][last()]", document.body).iterateNext().getBoundingClientRect().top);
If you need to scroll to the first occurrece, not the last one, delete [last()]
from this code.
You can also use what google is using to scroll to and highlight specific portions of a search result when you visit the page.
It generates a URL like this:
https://www.inc.com/peter-roesler/heres-what-googles-new-highlight-feature-means-for-your-website.html#:~:text=If%20you%20see%20a%20featured,saw%20in%20the%20featured%20snippet.
It is kind of nifty. The syntax seems to be:
https://example.com/#:~:beginning_of_text,end_of_text
See the following blog post for a few more details:
https://web.dev/text-fragments/
It is supported by version 80 and beyond chromium based browsers. So, limited support right now, but depending on your use case, it could be useful.
精彩评论