0

当我尝试传递分布在几个块元素中的文本时,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)。

4

1 回答 1

2

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

如果您希望它在 IE < 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');
于 2012-09-18T18:25:25.617 回答