JavaScript window.find()不选择搜索词

时间:2012-09-16 08:56:05

标签: javascript find

当我尝试传递遍及几个块元素的文本时,window.find方法有效:

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
  <p>search me</p><b> I could be the answer</b>
</body>
</html>

的JavaScript

window.find("meI could be");

或者:

str = "me";
str+= "\n";
str+="I could be t";

window.find(str);

当搜索词之间存在<p>元素时会发生这种情况 最终结果应该是页面中文本的GUI选择,我不想搜索它是否存在。

我想知道如何在Firefox(至少)和Internet Explorer中实现这一目标 注意:我无法更改dom(例如更改为内联显示)。

修改
这是我在@Alexey Lebedev的评论之后尝试过的,但它也找到了脚本(标签[...]文字):

我可以让它更简单吗? (优于)?

function nativeTreeWalker(startNode) {
    var walker = document.createTreeWalker(
        startNode, 
        NodeFilter.SHOW_TEXT, 
        null, 
        false
    );
    var node;
    var textNodesV = [];
    var textNodes = [];
    node = walker.nextNode();

    while(node ) {
      if(node.nodeValue.trim()){
        textNodes.push(node);
        textNodesV.push(node.nodeValue);
        //console.log(node.nodeValue);
      }
        node = walker.nextNode();
    }
  return [textNodes,textNodesV];
}

var result = nativeTreeWalker(document.body);
var textNodes = result[0];
var textNodesV = result[1];

var param = " Praragraph.Test 3 Praragr";
paramArr = param.split(/(?=[\S])(?!\s)(?=[\W])(?=[\S])/g);
//Fix split PARAM
for(i=0;i<paramArr.length-1;i++){
  paramArr[i]= paramArr[i]+paramArr[i+1].charAt(0);
  paramArr[i+1] = paramArr[i+1].substring(1,paramArr[i+1].length);
}
//Fix last element PARAM
if(paramArr[paramArr.length-1] === ""){
  paramArr.splice(paramArr.length-1,1);
}
//console.log(paramArr);
var startNode,startOffset,sFound=false,
    endNode,endOffset;
for(i=0;i<paramArr.length;i++){
  for(j=0;j<textNodesV.length;j++){
    //Fully Equal
    var pos = textNodesV[j].indexOf(paramArr[i]);
    if(pos != -1){
      if(!sFound){
        startNode = textNodes[j];
        startOffset = pos;
        sFound=true;
      }else{
        endNode = textNodes[j];
        endOffset = pos+paramArr[i].length;
        break;
      }
    }
  }
}
console.log(startNode);
console.log(startOffset);
console.log(endNode);
console.log(endOffset);

var range = document.createRange();
range.setStart(startNode,startOffset);
range.setEnd(endNode,endOffset);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

注意:没有jQuery(只有Raw JS)。

1 个答案:

答案 0 :(得分:2)

JS Bin演示:http://jsbin.com/aqiciv/1/

如果你想在IE中使用它&lt; 9你需要添加特定于MS的选择代码(噩梦),或者使用Rangy.js(非常重)。

function visibleTextNodes() {
    var walker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_ALL,
        function(node) {
            if (node.nodeType == 3) {
                return NodeFilter.FILTER_ACCEPT;
            } else if (node.offsetWidth && node.offsetHeight && node.style.visibility != 'hidden') {
                return NodeFilter.FILTER_SKIP;
            } else {
                return NodeFilter.FILTER_REJECT;
            }
        },
        false
    );

    for (var nodes = []; walker.nextNode();) {
        nodes.push(walker.currentNode);
    }
    return nodes;
}

// Find the first match, select and scroll to it.
// Case- and whitespace- insensitive.
// For better scrolling to selection see https://gist.github.com/3744577
function highlight(needle) {
    needle = needle.replace(/\s/g, '').toLowerCase();

    var textNodes = visibleTextNodes();

    for (var i = 0, texts = []; i < textNodes.length; i++) {
        texts.push(textNodes[i].nodeValue.replace(/\s/g, '').toLowerCase());
    }

    var matchStart = texts.join('').indexOf(needle);
    if (matchStart < 0) {
        return false;
    }

    var nodeAndOffsetAtPosition = function(position) {
        for (var i = 0, consumed = 0; consumed + texts[i].length < position; i++) {
            consumed += texts[i].length;
        }
        var whitespacePrefix = textNodes[i].nodeValue.match(/^\s*/)[0];
        return [textNodes[i], position - consumed + whitespacePrefix.length];
    };

    var range = document.createRange();
    range.setStart.apply(range, nodeAndOffsetAtPosition(matchStart));
    range.setEnd.apply(  range, nodeAndOffsetAtPosition(matchStart + needle.length));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    range.startContainer.parentNode.scrollIntoView();
}

highlight('hello world');