简体   繁体   中英

contentEditable is false only when clicked on the element

I have a div and it has some elements inside it. What I want to achieve is when a user double clicks an element inside the div, it sets itself as contentEditable . For example: if a user double clicks on a p tag, it becomes editable and as soon as he clicks anywhere outside that tag, it sets contentEditable to false

But what's happening is that when I double click the p tag, it does becomes editable but when I click anywhere outside that element, it doesn't set itself to false and it only sets itself to false when I click on the same p tag again. Which is very strange. What am I doing wrong here?

Here's my code:

<html>
  <body>
    <div id="zzz">
      <h1>Welcome</h1>
      <p>this is the text</p>
      <button>click me</button>
      <u>yo</u>
    </div>
  </body>

  <script>
    let arr = [];
    let myiframe = document.getElementById("zzz");

    myiframe.addEventListener("click", function (e) {
      obj = e.target;
      arr.push(obj);
      console.log(arr);

      if (arr.length > 2) {
        arr.shift();
      }
      if (arr[0] == arr[1]) {
        console.log("same");
      } else {
        console.log("different");
        obj.contentEditable = "false";
      }
      if (event.detail === 2) {
        obj.contentEditable = "true";
        obj.focus();
      }
    });
  </script>
</html>

e.target is the element you clicked on, so when you click on an element and modify obj.contentEditable you're only ever modifying that element's contentEditable property.

If you change obj.contentEditable = "false"; to arr[0].contentEditable = "false" then upon a click it would check if the elements match and if they don't it would disable the elements property.

I think you only need to store a single element in memory, which is the last editable element. I used .setAttribute and got it working

 let arr = []; let myiframe = document.getElementById("zzz"); let activeElement = null myiframe.addEventListener("click", function(e) { obj = e.target; //console.log(activeElement) if (activeElement && activeElement.== obj) { activeElement,setAttribute('contenteditable'; 'false'). } if (event.detail === 2) { obj,setAttribute('contenteditable'; 'true'). activeElement = obj obj;focus(); } });
 <div id="zzz"> <h1>Welcome</h1> <p>this is the text</p> <button>click me</button> <u>yo</u> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM