在可編輯內容 使用可編輯內容 解決方案概述 為了解決此問題,我們存儲當前遊標位置當 div 失去焦點時並在它重新獲得焦點時恢復它。這是一個跨主要瀏覽器工作的實現: 此解決方案涵蓋了重新聚焦時標位置的恢復以及單擊時恢復選擇的可選行為。它與所有主要瀏覽器相容,並為可編輯內容 var savedRange; // Variable to store the saved selection
var isInFocus; // Flag to track focus state
function saveSelection() {
if (window.getSelection) {
// Browser-specific logic to save the selected range
savedRange = window.getSelection().getRangeAt(0);
}
}
function restoreSelection() {
isInFocus = true;
document.getElementById("area").focus();
if (savedRange != null) {
// Browser-specific logic to restore the saved range
if (window.getSelection) {
var s = window.getSelection();
s.removeAllRanges();
s.addRange(savedRange);
}
}
}
// Optional code for selection restoration on click
function cancelEvent(e) {
if (isInFocus == false && savedRange != null) {
e.stopPropagation();
e.preventDefault();
restoreSelection();
}
}
// Event handlers for saving and restoring selection
$(document).ready(function() {
$("#area").focus(function() {
isInFocus = true;
});
$("#area").blur(function() {
isInFocus = false;
saveSelection();
});
$("#area").mouseup(function() {
saveSelection();
});
$("#area").keyup(function() {
saveSelection();
});
$("#area").focusin(function() {
restoreSelection();
});
// Optional event handlers for restoring selection on click
$("#area").mousedown(function(e) {
return cancelEvent(e);
});
$("#area").click(function(e) {
return cancelEvent(e);
});
});
以上是如何在 ContentEditable 中保持遊標位置``?的詳細內容。更多資訊請關注PHP中文網其他相關文章!