Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

php - 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 built in function for both the find text and scroll.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...