How to preserve text selection when opening a jQuery dialog

廉价感情. 提交于 2019-12-20 03:48:16

问题


Using jQuery's dialog I came across the following quirk (tested in FF3):

  1. User selects text
  2. In code, open up a jQuery dialog
  3. BUG: the text gets unselected

(text could be in a textarea or just an HTML on the page)

So, to me it seems like a funny (and annoying) bug or a quirk, but maybe there's a good explanation for that. And what interests me most, is how to preserve this text selection after opening the dialog?

Here's some code:

function getSelectedText() {
 var t;
 if (d.getSelection) t = d.getSelection();
 else if(d.selection) t = d.selection.createRange();
 if (t.text != undefined) t = t.text;
 if (!t || t=='') {
  var a = d.getElementsByTagName('textarea');
  for (var i = 0; i < a.length; ++i) {
   if (a[i].selectionStart != undefined && a[i].selectionStart != a[i].selectionEnd) {
    t = a[i].value.substring(a[i].selectionStart, a[i].selectionEnd);
    break;
   }   
  }   
 }   
 return t;
}

 $("#dialog").dialog({
    autoOpen: false,
    bgiframe: false,
    height: 60,
    width: 80,
    modal: false,
    show: 'highlight',
    title: 'wc'});
 alert(getSelectedText()); // Text is here      
 $("#dialog").dialog("open");
 alert(getSelectedText()); // Text is not selected here :( damn! 

Thanks!


回答1:


The jQuery dialog will take the user's focus ( you should see one of the buttons selected on the dialog ). Browsers only have 1 focus so you lose whatever they had selected.

You should just retrieve the start and end positions of the user's selection before you do the dialog, and then reselected it after the dialog goes away.

I don't have any example code for getting and setting user's selection, but a web search should find you some.

Something like :

$("dialog").focus(function() {
  // save the selection
}).blur(function() {
  // set the text selection
});

[edited (Nickolay): see Keep text selection when focus changes for more code]



来源:https://stackoverflow.com/questions/824833/how-to-preserve-text-selection-when-opening-a-jquery-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!