Home >Web Front-end >HTML Tutorial >Discussion on the issue of iframe node initialization_HTML/Xhtml_Web page production

Discussion on the issue of iframe node initialization_HTML/Xhtml_Web page production

WBOY
WBOYOriginal
2016-05-16 16:38:341234browse

Today I suddenly wanted to review the principles of making a rich text editor. So I started doing it step by step without saying a word. Because I wrote a simple rich text editor a year ago, I probably still have some impressions. But when I ran the code I wrote, I found a problem:

Copy the code
The code is as follows:

var ifr = document.createElement('iframe');
ifr.width = 300;
ifr.height = 300;
var idoc = ifr.contentDocument || ifr .contentWindow.document;
idoc.designMode = 'on';
idoc.contentEditable = true;
idoc.write('');
document.body.appendChild(ifr);

Take a look at the code above. Have you found any errors?

I think if there are no children who have had similar experiences to me, they probably won’t be able to see what’s wrong with this code. So you might as well go for a run, maybe you will find the problem soon.

Let me reveal the answer below:

This code will throw an object not found exception. Which object cannot be found? The document object cannot be found, what? How is it possible that the document object cannot be found? Of course, this document object is the document object of the iframe. Anyone who has done rich text knows that you must first obtain the document object of the iframe before making it editable. But why can't we get the document object? I won’t be too pretentious here. Let me talk about my solution process.

First of all, I went to Google and found that the way I got the document was correct. Then I wondered if it was Chrome? Doesn't Chrome support these two objects? So I switched to Firefox. The result is still the same. Then what is certain is that it must be a problem with your own code.

Later, by comparing the code on the Internet, I found that the position of my appendChild was a bit wrong, so I moved it ahead of time to get the document object:

Copy code
The code is as follows:

var ifr = document.createElement('iframe');
ifr.width = 300;
ifr. height = 300;
document.body.appendChild(ifr);
var idoc = ifr.contentDocument || ifr.contentWindow.document;
idoc.designMode = 'on';
idoc.contentEditable = true;
idoc.write('