2012-07-02 6 views
11

Estoy trabajando en una aplicación web que permite a un usuario seleccionar texto, hacer clic en un botón y guardar el texto resaltado. Esto funciona muy bien en los navegadores de escritorio, (Chrome para este ejemplo), pero en iOS tengo problemas con la selección de texto nativo, donde el usuario puede cambiar el texto seleccionado.Cómo capturó el rango de texto seleccionado en iOS después de la expansión de selección de texto

Aquí está el jsFiddle que muestra el problema (problema sólo existe en iOS): http://jsfiddle.net/JasonMore/gWZfb/

  1. usuario inicia la selección del texto

  2. usuario expande su selección de texto y hace clic en "Mostrar el texto seleccionado anteriormente "

  3. Sólo la primera palabra seleccionada" el "aparece, a pesar de que yo quiero" el camino del righteou s hombre "

1 Begin begin iOS text selection

2 Seleccionar texto y el botón expand text golpeó

3 Sólo "El" Only The

Aquí está la JS estoy usando:

$(function() { 
    $('#actionButton').click(function() { 
     $('#result').text(selectedRange.toString()); 
    }); 

    $('#slipsum').on('mouseup touchend','p', function() { 
     getSelectedRange(); 
    }); 
}); 

var selectedRange = null; 

var getSelectedRange = function() { 
    if (window.getSelection) { 
     selectedRange = window.getSelection().getRangeAt(0); 
    } else { 
     selectedRange = document.getSelection().getRangeAt(0); 
    } 
};​ 

HTML:

<h3>Selected Text:</h3> 
<p id="result"> 
</p> 
<br/> 
<p> 
    <input type="button" id="actionButton" value="Show the selected text above" /> 
</p> 
<!-- start slipsum code --> 
<div id="slipsum"> 
<h1>Is she dead, yes or no?</h1> 
<p>Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it? Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it? No? Well, that's what you see at a toy store. And you must think you're in a toy store, because you're here shopping for an infant named Jeb. </p> 

<h1>So, you cold?</h1> 
<p>The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee. </p> 

<h1>I'm serious as a heart attack</h1> 
<p>Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it? Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it? No? Well, that's what you see at a toy store. And you must think you're in a toy store, because you're here shopping for an infant named Jeb. </p> 

<h1>Is she dead, yes or no?</h1> 
<p>Like you, I used to think the world was this great place where everybody lived by the same standards I did, then some kid with a nail showed me I was living in his world, a world where chaos rules not order, a world where righteousness is not rewarded. That's Cesar's world, and if you're not willing to play by his rules, then you're gonna have to pay the price. </p> 

<h1>Is she dead, yes or no?</h1> 
<p>Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends. </p> 
</div> 
<!-- please do not remove this line --> 

<div style="display:none;"> 
<a href="http://slipsum.com">lorem ipsum</a></div> 

<!-- end slipsum code --> 
​ 
+2

Dar este plugin de jQuery una oportunidad y ver si funciona http: // jamesmgreene .github.com/jquery.textSelect/ –

+0

Es curioso, me siento justo detrás de James. ¿Estás trabajando en Eagan también entonces? –

+0

Los mouseups y mousedowns no se traducen en iOS. Los cambié a touchstart y touchend, y tengo algo más cerca. Gracias –

Respuesta

12

Para cualquier persona que se topa con este problema en el futuro, aquí es la resolución:

http://jsfiddle.net/JasonMore/gWZfb/

$(function() { 
    $('#actionButton').click(function() { 
     if (selectedRange) { 
      $('#result').text(selectedRange.toString()); 
      clearInterval(timer); 
     } 
    }); 

    timer = setInterval(getSelectedRange, 150); 
}); 

var timer = null; 

var selectedRange = null; 

var getSelectedRange = function() { 
    try { 
     if (window.getSelection) { 
      selectedRange = window.getSelection().getRangeAt(0); 
     } else { 
      selectedRange = document.getSelection().getRangeAt(0); 
     } 
    } catch (err) { 

    } 

};​ 
+0

Sí, eso es todo lo que puede hacer ... totalmente lo odio, pero probablemente incorporaré esto en jquery.textSeleccione como un comportamiento predeterminado para toque dispositivos de todos modos. :( –

+0

Sí, es bastante feo, pero es un caso tan raro, no puedo imaginar que muchas aplicaciones lo hagan. –

+0

FYI, agregó un problema: https://github.com/JamesMGreene/jquery.textSelect/issues/10 –

Cuestiones relacionadas