JS enables double clicking the content to become editable

  • 2021-07-26 06:05:01
  • OfStack

We often see interactive functions on some websites. 1 Some user information can be directly double-click the text box, and enter new information here to modify, without pressing the OK button, etc. .

I checked a lot of information on the Internet, but there is a small bug, that is, when the focus is obtained, the position of the cursor is at the beginning of the text box content, so the user needs to re-select the cursor position under 1 when editing, and this interaction feels bad; Later, new information was found to solve this problem, hoping to help more people.

Code section:

Note: Set the content of the selected text or set the cursor position


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JS Realize double-click edit to modify status </title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript">
  function ShowElement(element) {
    var oldhtml = element.innerHTML;
    // Create a new input Element 
    var newobj = document.createElement('input');
    // Add a type to a new element 
    newobj.type = 'text';
    // Add for the new element value Value 
    newobj.value = oldhtml;
    // Add a cursor leave event for a new element 
    newobj.onblur = function() {
      element.innerHTML = this.value == oldhtml ? oldhtml : this.value;
      // When triggered, judge whether the value of the added element is empty, if it is empty, it will not be modified, and the original value will be returned  
    }
    // Set the child node of this label to be empty 
    element.innerHTML = '';
    // Add the child nodes of the label, input Object 
    element.appendChild(newobj);
    // Set the content of the selected text or set the cursor position (two parameters: start,end ; start For the starting position, end Is the end position; If the start position and end position are the same, it is the cursor position) 
    newobj.setSelectionRange(0, oldhtml.length);
    // Set the get cursor 
    newobj.focus();
  }
</script>
</head>
<body>
  <dl>
    <dt> Your username :</dt>
    <dd ondblclick="ShowElement(this)">3 Pedestrian </dd>
    <dt> Your personality profile </dt>
    <dd ondblclick="ShowElement(this)">3 People, there must be my teacher! </dd>
  </dl>
</body>
</html>

Double-click event: ondblclick


Related articles: