简体   繁体   English

以编程方式选择文本Safari

[英]Selecting text Programmatically Mobile Safari

I'm having trouble selecting text on my site. 我在选择网站上的文本时遇到问题。 I have a div block and want all the text inside to be selected when the div block is touched on iPhone/Android. 我有一个div块,并希望在iPhone / Android上触摸div块时选择里面的所有文本。 So far I've tried the method at: Selecting text in mobile Safari on iPhone 到目前为止,我已经尝试了以下方法: 在iPhone的移动Safari中选择文本

Like so: 像这样:

<div ontouchstart="this.selectionStart=0; this.selectionEnd=this.value.length;">

I also tried creating a function in my JS file to do this based on recommendations from different sources: 我还尝试根据不同来源的建议在JS文件中创建一个函数来执行此操作:

HTML 的HTML

<div ontouchstart="touchStart(event, this);>

JS JS

function touchStart(event, obj) {
  var range = window.getSelection();
  var sel = window.getSelection()

  range.setStart(obj, 0);
  range.setEnd(obj, obj.innerHTML.length);
  sel.removeAllRanges();
  sel.addRange(range);
  //range.execCommand("BackColor", false, colour);
}

So far neither method seems to work. 到目前为止,这两种方法似乎都不起作用。 One error I seem to get using the second method while testing on Safari on iPhone is: 在iPhone上的Safari上进行测试时,我似乎使用第二种方法的一个错误是:

JavaScript: Error undefined TypeError: 'undefined' is not an object

selectionStart and selectionEnd are properties of textareas and text inputs only, so they're out. selectionStartselectionEnd仅是文本区域和文本输入的属性,因此它们不存在。 Mobile Safari has the same selection API as all other major browsers but you can only affect the visible selection if it's already displayed. Mobile Safari与所有其他主要浏览器具有相同的选择API,但是只有在可见选择已显示的情况下,您才可以对其进行选择。

HTML: HTML:

<div ontouchstart="selectElementContents(this);">

JS: JS:

function selectElementContents(el) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(el);
    sel.removeAllRanges();
    sel.addRange(range);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM