问题描述
我需要一些关于iPhone上的JavaScript的帮助 UIWebView
;
我有如下的HTML:
I need some help about JavaScript on iPhone UIWebView
;
I have HTML like below:
<html>
<head>
<title>Example</title>
</head>
<body>
<span>this example for selection <b>from</b> UIWebView</span>
</body>
</html>
我想进行选择,然后添加< span> code>用颜色标记HTML中的选定文本,就像电子书阅读器一样写一个注释。
I want to make a selection, and add
<span>
tag with color to the selected text in HTML to write a note just like an e-book reader.
这是我的JavaScript代码text:
This is my JavaScript code to get the selected text:
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];
这很好,并将选定的文本返回给我。
This works good, and returns me the selected text.
另外这个用于添加新标记的JS代码:
Also this JS code for adding a new tag:
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];
我的问题是这样的:
如果我选择example HTML文本)文本来自 WebView
,它可以工作,因为它不包含任何标签。
但是如果我选择selection from在HTML文本中)来自 WebView
的文本,它不起作用,因为它启动了< b>
的标签,和< / b>
超出了我的选择范围,因此我无法在< b> 和
< / b>
。
My problem is so:
if I select "example" (look at the HTML text) text from WebView
, it works, because it doesn't contain any tag.
But if I select "selection from" (look at the HTML text) text from WebView
, it's not working, because it starts the tag of <b>
, and </b>
is out of my selection, then I can't add a new tag between <b>
and </b>
.
我该如何解决这个问题? $ b
How can I solve this problem?
推荐答案
推荐答案
由于这是一个
UIWebView
,这是Mobile Safari,你可能会失去很多分支机构获取选择。我建议使用内置于浏览器中的HiliteColor命令来使用 document.execCommand()
,并在整个选区上工作,即使它跨越元素边界:
Since this is a
UIWebView
, this is Mobile Safari and you can lose a lot of those branches for obtaining the selection. I would suggest using document.execCommand()
with the "HiliteColor" command, which is built into the browser and works on the whole selection even when it crosses element boundaries:
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";
}
这篇关于选择&在JavaScript中动态添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!