首页 >web前端 >js教程 >如何在 ContentEditable 中保持光标位置``?

如何在 ContentEditable 中保持光标位置``?

Barbara Streisand
Barbara Streisand原创
2024-11-12 08:59:02272浏览

How to Maintain Cursor Position in a ContentEditable ``?

在可编辑内容

中保持光标位置

使用可编辑内容

时对于元素,通常需要在元素重新获得焦点后保留光标位置。默认情况下,浏览器通常会在重新聚焦时将光标重置到文本的开头。

解决方案概述

为了解决此问题,我们存储当前光标位置当 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn