使用JavaScript 從TextBox 控制項取得選定文字
使用文字方塊時,您可能會遇到需要擷取選取文字的情況。本文旨在為此任務提供全面的解決方案,解決 Internet Explorer 6 所遇到的問題。
文字方塊中文字的選擇可以使用 JavaScript 的內建屬性來實現。對於符合標準的瀏覽器,selectionStart 和selectionEnd 屬性提供所選文字的範圍。但是,對於 Internet Explorer,需要使用選擇物件的解決方法。
function ShowSelection() {
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined) {
// Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
} else if (document.selection !== undefined) {
// Internet Explorer version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " selectedText);
}
最初,Internet Explorer 6 中出現了一個問題,導致上述程式碼無法正常運作。為了解決這個問題,在存取選擇物件之前新增了 focus() 呼叫。此外,將 ShowSelection() 函數附加到 onkeydown 事件可以為偵測所選文字提供穩定的解決方案。
document.onkeydown = function (e) {
ShowSelection();
};
為了進一步澄清,按鈕的問題源自於它們在 Internet Explorer 中取消選取文字的固有行為。因此,建議使用簡單的輸入按鈕。透過實作此解決方案,您可以有效地從文字方塊控制項中擷取選定的文本,從而克服 Internet Explorer 6 所遇到的挑戰。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3