1

I am trying to select text from mobile web browser on touch based mobile by moving touch on screen using javascript. I don't want to use long touch to select text. I am trying to get selected text just like browser on desktop not like mobile provided way.

When I am trying to select text page is scrolling. But Instead of scrolling I want text selection.

Please provide me way to select text.

4

2 回答 2

2

这不是一个开发问题,应该迁移到 SuperUser。但是要回答您的问题,通常在手机中,您需要双击并带上文本选择工具栏。

然后您需要使用两个选择器选择范围。

你想如何使用 JavaScript 来实现它?如果您正在选择一个无法选择的范围,请使用以下命令:

如果您可以将图像用于不可编辑的文本,则可以通过使用图像作为背景并对其进行处理来做到这一点:

body {font-family: 'Verdana'; font-size: 10pt;}
.editable {background: url('http://i.imgur.com/cAZvApm.png') -1px 1px no-repeat; text-indent: 8.5em; margin: 0 0 10px;}
<div contenteditable class="editable">Pages you view in incognito tabs won’t stick around in your browser’s history, cookie store, or search history after you’ve closed all of your incognito tabs. Any files you download or bookmarks you create will be kept. Learn more about incognito browsing.</div>

<div>Now try to edit the above text and check out!</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
  if (document.body.createTextRange) {
    var range = document.body.createTextRange();
    range.moveToElementText(document.querySelectorAll(".editable")[0]);
    range.select();
  } else if (window.getSelection) {
    var selection = window.getSelection();        
    var range = document.createRange();
    range.selectNodeContents(document.querySelectorAll(".editable")[0]);
    selection.removeAllRanges();
    selection.addRange(range);
  }
  document.querySelectorAll(".editable")[0].focus();
</script>

预习:

注意:由于这是摘自我的回答,我想这不能被视为抄袭!

于 2014-11-04T15:01:03.007 回答
1

(我认为大多数)移动浏览器在点击触发之前使用 300 毫秒的延迟。此延迟允许用户双击以缩放、选择文本等。

如果要消除这种延迟,可以使用 fastclick.js:https ://github.com/ftlabs/fastclick

要使用 javascript 选择文本,您可以执行以下操作:

<span id="foo" >bar</span>

在你的脚本中:

 function selectText(element) {
    var doc = document;
    var text = doc.getElementById(element);    

    if (doc.body.createTextRange) { // ms
        var range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) { // moz, opera, webkit
        var selection = window.getSelection();            
        var range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

selectText('foo');
于 2014-11-04T15:05:55.447 回答