Toggle contentEditable on click

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

I'm trying to make a div contentEditable when it is clicked, and then set contentEditable to false on mouseout, but I've had no success so far. Clicking a link appears to highlight it, but otherwise does nothing at all:

http://jsfiddle.net/GeVpe/19/

<div id="content" contentEditable="true" onclick = "this.contentEditable = true;" onmouseout = "this.contentEditable = false;">     Surprisingly, <a href="http://google.com">clicking this link does nothing at all.</a> How can I fix this problem? </div>

I expected the link to take me to the linked page when it was clicked, but instead, it was highlighted when clicked and did nothing else. How can I fix this problem?

回答1:

Don't ever use inline html script declaration, thats a bad practice. I think the reason your link doesn't do anything is, that the event listener bubbled/propagated over it and changed its default onclick event, when you set it for your div.

I suggest you do something like this.

        window.onload = function() {             var div = document.getElementById('editable');             div.onclick = function(e) {                 this.contentEditable = true;                 this.focus();                 this.style.backgroundColor = '#E0E0E0';                 this.style.border = '1px dotted black';             }              div.onmouseout = function() {                 this.style.backgroundColor = '#ffffff';                 this.style.border = '';                 this.contentEditable = false;             }         }          // And for HTML          <div id="content">             <span id='editable'>Surprisingly,</span>             <a href="http://google.com">clicking this link does nothing at all.</a>         </div>


回答2:

 Here we can make html element editable true and false using this code.       $( "#mylabel" ).click(function() { // we get current value of html element         var value = $('#editablediv').attr('contenteditable'); //if its false then it make editable true     if (value == 'false') {         $('#editablediv').attr('contenteditable','true');     }     else { //if its true then it make editable false         $('#editablediv').attr('contenteditable','false');     }     });


回答3:

Try setting the target to blank:

<div id="content" contentEditable="true" onclick = "this.contentEditable = true;" onmouseout = "this.contentEditable = false;">     Surprisingly, <a href="http://google.com" target = "blank">clicking this link does nothing at all.</a> How can I fix this problem? </div>


转载请标明出处:Toggle contentEditable on click
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!