对于 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);
我能够获取包含文本节点的元素
最佳答案
试试这个:
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();
基本上与您的过滤相同(我只是添加了一个缺少的括号)。这将为您提供与您的字符串匹配的第一个(如果有)文本节点。但由于您无法直接获取 DOM 中的文本节点位置(请参阅 this question ),您可能想尝试一个简单的技巧,将其包装在 span 元素内,然后检索偏移量以滚动页面:
if(matches.length > 0){
var offset = $(matches).wrap('<span>').parent().offset().top;
$('html, body').animate({scrollTop: offset}, 'slow');
}
fiddle 示例 here
关于javascript - 滚动到 JavaScript 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17417230/