开发者

Auto scroll to span element

开发者 https://www.devze.com 2023-01-26 18:54 出处:网络
I have anelement that contains (surprise!) an article. There开发者_JAVA百科 is a list of tags at the top of the page that are found in the article.

I have an element that contains (surprise!) an article.

There开发者_JAVA百科 is a list of tags at the top of the page that are found in the article. When a user clicks a tag it any matching words in the article are highlighted.

What I am having trouble with is then automatically scrolling to the highlighted word.

Is there any way to do this with javascript/jQuery?

The following is my code to find the word and highlight it:

$(".article-tags a.toggle").live("click", function () {
        var $this = $(this);
        var $p = $this.closest("p");
        if ($p.find("span.highlight").length == 0) {
            $("#viewer .article-body").highlight($this.text());
            $this.highlight($this.text());
            document.getElementById("viewer").scrollTop = $p.find("span.highlight").offsetTop;
        }
        else {
            $("#viewer .article-body").removeHighlight();
            $p.removeHighlight();
        }
        return false;
    });

Thanks.


Several ways to accomplish that.

  • jQuerys .animate() with scrollTop set to elements.offset().top
  • $(window).scrollTop(element.offset().top);
  • element.scrollIntoView();

.scrollIntoView() is a native method which you can call on a DOM node directly.


$('span.highlight').first().prepend('<a class="highlighted" name="hightlighted" />');
window.location.hash = '#highlighted';

That should do it. You're adding an anchor just before the element, then scrolling to it. You might want to put in a $('a.highlighted').remove() before this to clear any previous additions.

0

精彩评论

暂无评论...
验证码 换一张
取 消