简体   繁体   中英

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. So far I've tried the method at: Selecting text in mobile Safari on iPhone

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:

HTML

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

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:

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

selectionStart and selectionEnd are properties of textareas and text inputs only, so they're out. 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.

HTML:

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

JS:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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