我需要有关iPhone上的JavaScript的一些帮助UIWebView
;
我有如下的HTML:
<html>
<head>
<title>Example</title>
</head>
<body>
<span>this example for selection <b>from</b> UIWebView</span>
</body>
</html>
我要进行选择,然后将带有颜色的
<span>
标签添加到HTML中的所选文本中,以像电子书阅读器一样书写笔记。这是我的JavaScript代码,用于获取所选文本:
NSString *SelectedString = [NSString stringWithFormat:@"function getSelText()"
"{"
"var txt = '';"
" if (window.getSelection)"
"{"
"txt = window.getSelection();"
" }"
"else if (document.getSelection)"
"{"
"txt = document.getSelection();"
"}"
"else if (document.selection)"
"{"
"txt = document.selection.createRange().text;"
"}"
"else return;"
"alert(txt);"
"}getSelText();"];
[webView stringByEvaluatingJavaScriptFromString:SelectedString];
这样效果很好,并向我返回了所选文本。
另外,此JS代码用于添加新标签:
NSString *AddSpanTag = [NSString stringWithFormat:@"function selHTML() {"
"if (window.ActiveXObject) {"
"var c = document.selection.createRange();"
"return c.htmlText;"
"}"
"var nNd = document.createElement(\"span\");"
"var divIdName = \'myelementid\';"
"var ColorAttr = \"background-color: #ffffcc\";"
"nNd.setAttribute(\'id\',divIdName);"
"nNd.setAttribute(\'style\',ColorAttr);"
"var w = getSelection().getRangeAt(0);"
"w.surroundContents(nNd);"
"return nNd.innerHTML;"
"}selHTML();"];
[webView stringByEvaluatingJavaScriptFromString:AddSpanTag];
我的问题是这样的:
如果我从
WebView
中选择“示例”(查看HTML文本)文本,则该文本有效,因为它不包含任何标签。但是,如果我从
WebView
中选择“selection from”(请查看HTML文本)文本,则该文本不起作用,因为它开始了<b>
的标记,而</b>
不在我的选择之内,那么我就无法在<b>
之间添加新标记和</b>
。我怎么解决这个问题?
最佳答案
由于这是UIWebView
,所以这是Mobile Safari,您可能会失去很多分支来获取选择。我建议将document.execCommand()
与“HiliteColor”命令一起使用,该命令内置于浏览器中,即使跨越元素边界也适用于整个选择:
var sel = window.getSelection();
if (!sel.isCollapsed) {
var selRange = sel.getRangeAt(0);
document.designMode = "on";
sel.removeAllRanges();
sel.addRange(selRange);
document.execCommand("HiliteColor", false, "#ffffcc");
sel.removeAllRanges();
document.designMode = "off";
}