以下是我在 UIWebView 中使用的一些 HTML:
<div id = "1">
<span style = "background-color:red">
<a href = "10&20">
This is a link
</a>
</span>
</div>
点击链接后,我想以编程方式选择 UIWebView 中的链接文本(因此“这是一个链接”现在将使用蓝色 iOS 文本选择工具突出显示)。这就是为什么我在 a 标签的 href 中发送一些范围信息的原因。这是我用来尝试进行此编程选择的调用:
//set content editable true
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"selectElementContentsInRange(document.getElementById('1'), 10, 20)"]];
这是 JavaScript 函数:
function selectElementContentsInRange(el, first, second) {
var range = document.createRange();
alert("Makes it here");
range.setStart(el.firstChild, first);
alert("Doesn't make it here");
range.setEnd(el.firstChild, second);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
正如您在警报中看到的那样,它并没有超过range.setStart()
调用而不抛出错误。 Safari javascript 调试器给我这个错误:
IndexSizeError: DOM Exception 1: Index or size was negative, or greater than the allowed value.
我尝试了很多不同的方法,但没有任何效果。我完全束手无策,非常感谢一些关于如何做到这一点的见解。我开始怀疑是否有可能以编程方式在 UIWebView 中选择文本。我错了吗?有人这样做过吗?