我有一个包含(惊奇!)文章的元素。

在页面顶部,有在文章中找到的标签列表。
用户单击标签时,它将突出显示文章中所有匹配的单词。

然后,我遇到的问题是自动滚动到突出显示的单词。

有没有办法用javascript / jQuery做到这一点?

以下是我找到该单词并将其突出显示的代码:

$(".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;
    });


谢谢。

最佳答案

有几种方法可以做到这一点。


.animate()设置为scrollTop的jQuerys elements.offset().top
$(window).scrollTop(element.offset().top);
element.scrollIntoView();


.scrollIntoView()是本机方法,您可以直接在DOM节点上调用。

09-26 23:39
查看更多