2

我已经使用 javascript 在 uiwebview 中设置了一个搜索,效果很好,但我希望能够跳转到搜索结果中找到的下一个单词。通过使用以下代码,我已成功使视图滚动到第一个实例:

   function uiWebview_HighlightAllOccurencesOfStringForElement(element,keyword) {

//declared a var for height

if (element) {
    if (element.nodeType == 3) {        // Text node
        while (true) {
            //if (counter < 1) {
            var value = element.nodeValue;  // Search for keyword in text node
            var idx = value.toLowerCase().indexOf(keyword);
            if (idx < 0) break;             // not found, abort

            //(value.split);

            //we create a SPAN element for every parts of matched keywords
            var span = document.createElement("span");
            var text = document.createTextNode(value.substr(idx,keyword.length));
            span.appendChild(text);
            span.setAttribute("id",keyword);
            span.setAttribute("class","uiWebviewHighlight");
            span.style.backgroundColor="black";
            span.style.color="white";

            uiWebview_SearchResultCount++;    // update the counter

            text = document.createTextNode(value.substr(idx+keyword.length));
            element.deleteData(idx, value.length - idx);
            var next = element.nextSibling;
            element.parentNode.insertBefore(span, next);
            element.parentNode.insertBefore(text, next);
            element = text;
            if(desiredHeight == 0)
            {
                var offset = {};
                offset.x = 0;
                offset.y =0;
                GetOffset(document.getElementById(keyword),offset);
                desiredHeight = offset.y-150;
                alert(desiredHeight);
                window.scrollTo(0,desiredHeight);
            }
        }


    } else if (element.nodeType == 1) { // Element node
        if (element.style.display != "none" && element.nodeName.toLowerCase() !=  
     'select') {
            for (var i=element.childNodes.length-1; i>=0; i--) {
   uiWebview_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);

            }
        }
     }
   }

  }

   function GetOffset (object, offset) {
  if (!object)
    return;
 offset.x += object.offsetLeft;
 offset.y += object.offsetTop;

  GetOffset (object.offsetParent, offset);
  }

现在我想在单击下一个按钮时跳转到下一个搜索字符串。我该怎么做?请给我建议。

4

2 回答 2

1

我将该代码用于下一个和上一个功能,它工作正常

function uiWebview_HighlightAllOccurencesOfNextStringForElement(element,keyword) {

    if (element) {
        if (element.nodeType == 3) {        // Text node
            while (true) {
                //if (counter < 1) {
                var value = element.nodeValue;  // Search for keyword in text node
                var idx = value.toLowerCase().indexOf(keyword);

                if (idx < 0) break;             // not found, abort

                var span = document.createElement("span");
                var text = document.createTextNode(value.substr(idx,keyword.length));
                span.appendChild(text);
                span.setAttribute("class","MyAppHighlight");
                text = document.createTextNode(value.substr(idx+keyword.length));
                element.deleteData(idx,value.length-idx);
                var next = element.nextSibling;
                element.parentNode.insertBefore(span,next);
                element.parentNode.insertBefore(text,next);
                element = text;
                span.scrollIntoView();
                span.style.backgroundColor = "yellow";

                span.style.color = "black";
                a.push(span);

                uiWebview_SearchResultCount++;



            }
        } else if (element.nodeType == 1) { // Element node
            if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
                for (var i=element.childNodes.length-1; i>=0; i--) {
                    uiWebview_HighlightAllOccurencesOfNextStringForElement(element.childNodes[i],keyword);
                }
            }
        }
    }
}

// the main entry point to start the search
function uiWebview_HighlightAllOccurencesOfNextString(keyword) 
`enter code here`{
    uiWebview_RemoveAllHighlights();
    uiWebview_HighlightAllOccurencesOfNextStringForElement(document.body, keyword.toLowerCase());

}

//And than In Your ViewContrlller Called this function on Next And Previous button method

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self highlightAllOccurencesOfNextString:searchbar.text];
}

- (NSInteger)highlightAllOccurencesOfNextString:(NSString*)str
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"UIWebViewSearch" ofType:@"js"];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
    [htmlWebView stringByEvaluatingJavaScriptFromString:jsString];

    NSString *startSearch = [NSString stringWithFormat:@"uiWebview_HighlightAllOccurencesOfNextString('%@')",str];
    [htmlWebView stringByEvaluatingJavaScriptFromString:startSearch];
    NSString *result = [htmlWebView stringByEvaluatingJavaScriptFromString:@"a.length"];
    currentPosition = [result intValue] - 1;
    return [result integerValue];

}

-(void)nextMethod
{
    currentPosition -= 1;
    NSString *nextScrollPosition =  [NSString stringWithFormat:@"a[%d].scrollIntoView()", currentPosition];
    [htmlWebView stringByEvaluatingJavaScriptFromString:nextScrollPosition];
}

-(void)previousMethod
{
    currentPosition += 1;
    NSString *previousScrollPosition =  [NSString stringWithFormat:@"a[%d].scrollIntoView()", currentPosition];
    [htmlWebView stringByEvaluatingJavaScriptFromString:previousScrollPosition];
}
于 2015-03-02T12:31:30.323 回答
1

这是我的功能,具有必要的功能:

// We're using a global variable to store the number of occurrences
var MyApp_SearchResultCount = 0;
var myCurrentCount = 0;

// helper function, recursively searches in elements and their child nodes
function MyApp_HighlightAllOccurencesOfStringForElement(element,keyword) {
    if (element) {
        if (element.nodeType == 3) {        // Text node
            while (true) {
                var value = element.nodeValue;  // Search for keyword in text node
                var idx = value.toLowerCase().indexOf(keyword);

                if (idx < 0) break;             // not found, abort

                var span = document.createElement("span");
                var text = document.createTextNode(value.substr(idx,keyword.length));
                span.appendChild(text);
                var str1 = "MyAppHighlight"+MyApp_SearchResultCount;
                span.setAttribute("class", "MyAppHighlight");
                span.setAttribute("id", str1);
                span.style.backgroundColor="yellow";
                span.style.color="black";
                text = document.createTextNode(value.substr(idx+keyword.length));
                element.deleteData(idx, value.length - idx);
                var next = element.nextSibling;
                element.parentNode.insertBefore(span, next);
                element.parentNode.insertBefore(text, next);
                element = text;
                MyApp_SearchResultCount++;  // update the counter
            }
        } else if (element.nodeType == 1) { // Element node
            if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
                for (var i=element.childNodes.length-1; i>=0; i--) {
                    MyApp_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
                }
            }
        }
    }
}

// the main entry point to start the search
function MyApp_HighlightAllOccurencesOfString(keyword) {
    MyApp_RemoveAllHighlights();
    MyApp_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
    myCurrentCount = MyApp_SearchResultCount;
    moveToNext();
}

// helper function, recursively removes the highlights in elements and their childs
function MyApp_RemoveAllHighlightsForElement(element) {
    if (element) {
        if (element.nodeType == 1) {
            if (element.className.indexOf("MyAppHighlight") > -1) {
                var text = element.removeChild(element.firstChild);
                element.parentNode.insertBefore(text,element);
                element.parentNode.removeChild(element);
                return true;
            } else {
                var normalize = false;
                for (var i=element.childNodes.length-1; i>=0; i--) {
                    if (MyApp_RemoveAllHighlightsForElement(element.childNodes[i])) {
                        normalize = true;
                    }
                }
                if (normalize) {
                    element.normalize();
                }
            }
        }
    }
    return false;
}

function moveToPrev()
{
    if (myCurrentCount < MyApp_SearchResultCount-1)
    {
        myCurrentCount++;
        document.getElementById("MyAppHighlight"+myCurentCount).scrollIntoView();
    }
    else{
        myCurrentCount = MyApp_SearchResultCount;
        window.scrollTo(0,0);
    }
}

function moveToNext()
{
    if (myCurrentCount > 0)
    {
        myCurrentCount--;
        document.getElementById("MyAppHighlight"+myCurentCount).scrollIntoView();
    }
    else{
        myCurrentCount = MyApp_SearchResultCount;
        window.scrollTo(0,0);
    }
}

// the main entry point to remove the highlights
function MyApp_RemoveAllHighlights() {
    MyApp_SearchResultCount = 0;
    myCurrentCount = 0;
    MyApp_RemoveAllHighlightsForElement(document.body);
}
于 2013-10-28T09:06:37.397 回答