2009-05-05 135 views
2

時,使用我碰到下面的怪癖(在FF3測試)來了jQuery的對話框保存文本選擇:如何打開一個jQuery對話框

  1. 用戶選擇文本
  2. 在代碼中,開闢一個jQuery對話框
  3. BUG:文本獲取未選擇

(文本可以在一個文本或只是網頁上的HTML)

因此,對我來說,這似乎是一個有趣(令人討厭)的錯誤或怪癖,但也許有一個很好的解釋。 最讓我感興趣的是如何在打開對話框後保留此文字選擇?

下面是一些代碼:

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! 

謝謝!

+0

據我所知,這是正常的行爲。如果您選擇文字,然後點擊頁面上的其他任何位置,選擇就會消失。 – Geoff 2009-05-05 13:34:08

回答

2

jQuery對話框將使用戶的焦點(你應該看到在對話框中選擇的按鈕之一)。瀏覽器只有一個焦點,所以你失去了他們選擇的任何東西。

您應該在執行對話框之前檢索用戶選擇的開始和結束位置,然後在對話框消失後重新選擇它。

我沒有任何示例代碼獲取和設置用戶的選擇,但網絡搜索應該找到你一些。

喜歡的東西:

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

[編輯(Nickolay):看到Keep text selection when focus changes更多代碼]