在可编辑内容 使用可编辑内容 解决方案概述 为了解决此问题,我们存储当前光标位置当 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中文网其他相关文章!