1

我正在尝试构建一个非常简单的网页阅读器作为培训项目。

这是我想做的事情:

  1. 将触摸的元素存储在 JS 变量中(touchedElement)
  2. 稍后突出显示该元素的子字符串

不幸的是,它不起作用。

有什么建议么?

这是我尝试存储触摸元素的方法:

    UITouch *aTouch = [touches anyObject];
    location = [aTouch locationInView:myWebView];
    NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).innerText", location.x, location.y];
    NSString *text = [myWebView stringByEvaluatingJavaScriptFromString:js];
    NSString *js2 = [NSString stringWithFormat:@"var touchedElement = document.elementFromPoint(%f, %f);", location.x, location.y];
    tagName = [myWebView stringByEvaluatingJavaScriptFromString:js2];

这是我尝试突出显示子字符串(Obj-C 部分)的方法:

NSString *startSearch   = [NSString stringWithFormat:@"uiWebview_HighlightRangeOfTouchedElement(%lu, %lu)", (unsigned long)characterRange.location, (unsigned long)characterRange.length];
[myWebView stringByEvaluatingJavaScriptFromString:startSearch];

这是我尝试突出显示子字符串(JS 部分)的方法:

// the main entry point to start the search
function uiWebview_HighlightRangeOfTouchedElement(idx, length) {
    uiWebview_RemoveAllHighlights();
    uiWebview_HighlightRangeOfTouchedElement(touchedElement, idx, length);
}

function uiWebview_HighlightRangeOfTouchedElement(element, idx, length)
    if (element) {
        if (element.nodeType == 3) {        // Text node
            while (true) {
                //if (counter < 1) {
                var value = element.nodeValue;  // Search for keyword in text node
                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, length));
                span.appendChild(text);

                span.setAttribute("class","uiWebviewHighlight");
                span.style.backgroundColor="yellow";
                span.style.color="black";

                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;
            }
        } 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_HighlightRangeOfTouchedElement(element.childNodes[i],keyword, idx, length);
                }
            }
        }
    }
}
4

1 回答 1

0

原来 Obj-C 部分工作正常,但 JS 被/坏了。这没东西看。

于 2013-08-27T14:56:32.283 回答