type in empty divs while contenteditable = true?

2019-06-13 13:56发布

问题:

why won't the cursor enter some of my divs when contenteditable is enabled?

also, why does my browser tell me there is nothing in the div when there is clearly a space character in it?!

var div = '<div> </div>'; 
div.innerHTML = undefined 

What gives?

回答1:

contenteditable does not apply to empty elements, so you may want to insert a non-breaking-space character into the empty elements you want to be able to edit

the non-breaking-space "&nbsp;" will act as a character when left on its own,
whereas a whitespace " " will only count as a character if placed after another character

    <div>" "</div> ----------------> innerHTML = undefined
    <div>"&nbsp;"</div> --------> innerHTML =

the gray box around &nbsp; means its an html character
so make sure you insert a "&nbsp" and not a " "

var nbsp = "&nbsp;",
    div = document.getElementById('id');
div.innerHTML = nbsp

jquery works too

var div = $('div#id')
div.html(nbsp1)