在javascript中滚动到文本

时间:2013-07-02 04:06:40

标签: javascript jquery dom

对于Google Chrome插件,我正在尝试滚动到包含给定字符串的DOM元素。但是,在过滤选择器之后,我在DOM中有点迷失。

$('*', 'body')
    .andSelf()
    .contents()
    .filter(function(){                     
        return this.nodeType === 3;
    })
    .filter(function(){
        // Only match when contains given string anywhere in the text       

        if(this.nodeValue.indexOf(givenString != -1){
            //idArr.push(this.offsetLeft);

            var ele = $(this);
                       $('html, body').animate({
                    scrollTop: ele.offset().top
                     }, 2000);                              
                return true;
            }

            return false;

    });

每当我尝试获得ele的顶部偏移时,我得到滚动条相对于文档的顶部偏移量。有任何想法吗?我认为在过滤器中使用$this可能是一个范围问题,但过滤器中的this应该引用当前的DOM元素。

编辑:

致电

var ele=$(this.parentNode);

我能够获得包含文本节点

的元素

2 个答案:

答案 0 :(得分:2)

试试这个:

var matches = $('body, body *').
        addBack().
        contents().
        filter(function(){                     
            return this.nodeType === 3;
        }).
        filter(function(){
        // Only match when contains given string anywhere in the text               
             if(this.nodeValue.indexOf(givenString) != -1)
               return true;
        }).first();

基本上你有相同的过滤(我刚添加了一个缺少的括号)。这将为您提供与您的字符串匹配的第一个(如果有)textnode。但是由于你无法直接在DOM中获取textnodes位置(请参阅this question),你可能想尝试一个简单的技巧,将其包装在span元素中,然后检索偏移量以滚动页面:

if(matches.length > 0){
    var offset = $(matches).wrap('<span>').parent().offset().top;
    $('html, body').animate({scrollTop: offset}, 'slow');
}

小提琴示例here

答案 1 :(得分:0)

el = $(":not(html, body, div, table, tbody, tr):contains('" + givenString + "')")

这将返回匹配的元素。然后你可以滚动到元素