【问题标题】:How to Select text on mobile web browser by moving touch on screen using javascript?如何通过使用javascript在屏幕上移动触摸来选择移动网络浏览器上的文本?
【发布时间】:2014-12-31 12:41:27
【问题描述】:

我正在尝试通过使用 javascript 在屏幕上移动触摸来从基于触摸的移动设备上的移动网络浏览器中选择文本。我不想使用长按来选择文本。我正在尝试获取选定的文本,就像桌面上的浏览器一样,而不是移动设备提供的方式。

当我尝试选择文本时,页面正在滚动。但我想要文本选择而不是滚动。

请提供选择文本的方法。

【问题讨论】:

  • 你可以使用触摸事件

标签: javascript mobile textselection touchmove mobile-chrome


【解决方案1】:

这不是开发问题,应该迁移到 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>

预览:

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

【讨论】:

    【解决方案2】:

    (我认为大多数)移动浏览器在点击触发之前使用 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');
    

    【讨论】:

    • 这和我的逻辑有什么不同?
    • 您发帖时可能正在输入我的答案。无论如何,我的回答中可能会有有价值的补充:)
    • 不错! :) 好的。好的! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2011-06-17
    相关资源
    最近更新 更多