特定的UIWebView选择(只有整个单词/句子)

Specific UIWebView Selections (only entire words/sentences)

本文关键字:单词 句子 UIWebView 选择      更新时间:2023-09-26

我希望用户只能在我的UIWebView中选择整个句子。我在UIWebView中使用我自己的UIMenuItem(一个书签按钮)。我要保存这个书签(核心数据),并想确定哪个句子/节的重点是在。我以编程方式布局html(从sqlite数据库建立),并有一个<span id="x">(其中x是一个可变整数)围绕每个句子。我知道亚马逊的Kindle应用程序只允许用户选择整个单词。我该怎么做呢?

谢谢!

您试过setMarkedText:selectedRange:了吗?

Apple developer lib

更新:

虽然你不能在UIWebView里面使用setMarkedText,但没有办法,只能使用JavaScript。我不知道,你是否可以操作你所显示的HTML页面?您可以在页面中添加此脚本。如果你不能操作这个页面,你应该在你的UIWebView中加载一个iframe来加载你的实际页面,在iframe之后添加这个脚本。

脚本如下:

document.addEventListener('mouseup', function(){
    if(getSelection().anchorNode != null ){
        var sel = getSelection(),
            range = sel.getRangeAt(0),
            nodeValue = sel.anchorNode.nodeValue,
            lastCharIndex = range.endOffset,
            firstCharIndex = range.startOffset,
            lastChar = nodeValue.substr(lastCharIndex, 1),
            firstChar = nodeValue.substr(firstCharIndex, 1);
        while(lastChar != (" " || ".")){
            lastChar = nodeValue.substr(lastCharIndex, 1);
            lastCharIndex++;
        };
        while(firstChar != " "){
            firstChar = nodeValue.substr(firstCharIndex, 1);
            firstCharIndex--;
        };
        range.setEnd(sel.anchorNode, lastCharIndex-1);
        sel.addRange(range);
        range.setStart(sel.anchorNode, firstCharIndex+2);
        sel.addRange(range);
    }
}, false);

我在iPhone上测试了一下,运行正常。

这是Demo(只需选择一些内容)。我在上面花了很多时间。我希望你喜欢。