最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Programmatically select text in UIWebView - Stack Overflow

programmeradmin3浏览0评论

I'm asking this question after 2 days of research. I've read all the related questions and answers in stackoverflow and google (including this question, which is very similar but without an answer) and still couldn't find a solution. Hopefully someone here will be able to help.

I have a UIWebView with some text loaded into it. I want to select part of the text programmatically, as if the user long-pressed on it.

I've tried executing this javascript code as a response to a click:

function selectEl(x,y)
{
    document.designMode = "on";
    var el = document.elementFromPoint(x, y);
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = document.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
    document.designMode = "off";
}

I've tried it with and without changing designMode to "off" at the end of the function. I know this code "selects" the correct element, because if I perform this mand

document.execCommand("BackColor", false, "#ffffcc");

it actually highlights the element I clicked on, but it doesn't cause a selection of the text. Any ideas on how to achieve this?

I'm asking this question after 2 days of research. I've read all the related questions and answers in stackoverflow and google (including this question, which is very similar but without an answer) and still couldn't find a solution. Hopefully someone here will be able to help.

I have a UIWebView with some text loaded into it. I want to select part of the text programmatically, as if the user long-pressed on it.

I've tried executing this javascript code as a response to a click:

function selectEl(x,y)
{
    document.designMode = "on";
    var el = document.elementFromPoint(x, y);
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = document.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
    document.designMode = "off";
}

I've tried it with and without changing designMode to "off" at the end of the function. I know this code "selects" the correct element, because if I perform this mand

document.execCommand("BackColor", false, "#ffffcc");

it actually highlights the element I clicked on, but it doesn't cause a selection of the text. Any ideas on how to achieve this?

Share Improve this question edited May 23, 2017 at 10:28 CommunityBot 11 silver badge asked Nov 21, 2012 at 10:43 Eli GanemEli Ganem 1,4791 gold badge13 silver badges26 bronze badges 15
  • zaldzbugz.posterous./… – Omarj Commented Nov 23, 2012 at 18:47
  • so still have the problem after read this one ???? – Omarj Commented Nov 23, 2012 at 20:07
  • I already saw this link and it doesn't describe how to achieve what I need. Thanks anyway. – Eli Ganem Commented Nov 24, 2012 at 12:08
  • if that does not help u, so that mean your problem is something else ??? – Omarj Commented Nov 24, 2012 at 12:22
  • see this one icab.de/blog/2010/01/12/search-and-highlight-text-in-uiwebview – Omarj Commented Nov 24, 2012 at 12:23
 |  Show 10 more ments

3 Answers 3

Reset to default 2 +50

This seems to be a bug in Mobile Safari. When I toggle contentEditable to true in touchstart and set it to false in touchend it works. If I remove those lines and refresh it still works. If I close Mobile Safari, clear the cache, and then re-open the document with the lines removed it stops working again.

I've updated the code below with a working version (although I removed the long-press for simplicity).

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

(function() {
    var node,
        range,
        offset,
        clientX,
        clientY;

    document.addEventListener("DOMContentLoaded", function() {
        document.body.addEventListener("touchstart", function(event) {
            var selection = window.getSelection();
            selection.removeAllRanges();

            clientX = event.touches[0].clientX;
            clientY = event.touches[0].clientY;

            range = document.caretRangeFromPoint(clientX, clientY);
            node = range.startContainer;
            offset = range.startOffset;

            document.body.contentEditable = "true";
            event.preventDefault();
        });
        document.body.addEventListener("touchmove", function(event) {
            var selection = window.getSelection(),
                range = document.caretRangeFromPoint(event.touches[0].clientX, event.touches[0].clientY),
                newRange = document.createRange();

            if(clientY < event.touches[0].clientY) {
                newRange.setStart(node, offset);
                newRange.setEnd(range.startContainer, range.startOffset);
            }
            else {
                newRange.setStart(range.startContainer, range.startOffset);
                newRange.setEnd(node, offset);
            }

            selection.removeAllRanges();
            selection.addRange(newRange);

            event.preventDefault();
        });
        document.body.addEventListener("touchend", function(event) {
            document.body.contentEditable = "false";
            event.preventDefault();
        });
    });
})();
</script>
<body>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempus volutpat mauris sed porta. Phasellus euismod malesuada eleifend. Donec mattis, orci quis scelerisque mattis, turpis sem pulvinar nisi, et sagittis nunc nisi sed nulla. Pellentesque pharetra consequat neque, ultrices mattis mauris auctor id. Aenean tincidunt turpis non odio gravida semper. Praesent feugiat, lorem at lacinia tristique, orci eros tincidunt leo, at adipiscing sapien felis at tellus. Phasellus ac est nec nibh posuere euismod vel vitae neque. Vestibulum mollis adipiscing urna ut tristique. Vivamus purus tortor, venenatis id aliquam nec, elementum et lacus. Praesent elementum purus eget sapien ornare laoreet. Vestibulum ac odio enim.
</body>
</head>
</html>

Just a thought: Make sure you are NOT using anything like this in your css:

* {
  -webkit-touch-callout: none;
   -webkit-user-select: none;
   user-select: none;
}

This prevents any text selections.

I came across this:

hitElem.style.backgroundColor = "highlight";
hitElem.style.color = "highlighttext";

Or, THIS SITE Has written some HORRIBLE scripting but it may help you :) It works with ranges.

发布评论

评论列表(0)

  1. 暂无评论