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

2019-09-22 11:33发布

当我试图通过其散播到几个块元素window.find方法dosent工作内容:

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(如改变显示inline)。

编辑:
下面是我@Alexey列别杰夫的评论后尝试过,但它也发现脚本(标签[...]文本):

我可以使它更简单吗? (更好)?

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(只生JS)。

Answer 1:

JS斌演示: 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');


文章来源: JavaScript window.find() does not select search term