Why is ContentEditable removing “ID” from div

喜你入骨 提交于 2019-11-29 08:49:48
Steerpike

The first issue, as Gary pointed out is the inconsistency in case although it won't affect IE as explorer getElementById goes against W3 specs and is not case sensitive.

Changing the exec command to be: document.execCommand("insertOrderedList",true,""); seems to get be objects for both alerts and also makes the code work a bit better in firefox (which wasn't working at all).

I guess my first question would be, do you really need to do this using execCommand? I know you're probably trying to do more than just insert an ordered list, but I'd hazard a guess that implementing what you're trying to do with the DOM would likely be a cleaner way to do it.

I'm adding an edit to this reply, because the more I play with your test code the more inconsistent my results are becoming. I get different results the first time I run it in different browsers and I get different results after running it a few times and then restarting the browser. To be perfectly honest this is exactly the kind of stuff you desperately want to avoid when doing javascript development so I'll reiterate my initial question. Do you really need to use this technique to achieve your goals. There are better and easier ways to do insertion into the DOM.

Try this;

<html>
<head>
<title></title>
<script type="text/javascript">
function addToList(text) {
        var list = document.getElementById('list');
        list.innerHTML += '<li>'+text+'</li>';
}
</script>
</head>
<body>

<div contentEditable="true" id="editBox" style="width: 300px; height: 100px; border:1px solid #ff0000;"> </div>
<ol id="list"></ol>

<button title="Ordered List" unselectable="on" onclick="addToList(document.getElementById('editBox').innerHTML)">Push me</button>


</body>
</html>

The above should give reliable results in most browsers. I've tested the above in FF3 and IE6.

Thanks for everyone’s help, anyone thinking of using “contentEditable” should read the other answers to my question and then think very hard before using “contentEditable”.

I have found that if I use an iframe e.g.

<iframe id=EditorIFrame >
</iframe>

And create the div that is editable in the iframe eg

theEditorIFrame = document.getElementById('EditorIFrame');  
theEditorDoc = theEditorIFrame.contentWindow.document;  
theEditorDoc.body.innerHTML = '<body><div contentEditable="true" id="EDITBOX"></div></body>';
theEditorDiv = theEditorDoc.getElementById("EDITBOX") 
theEditorDiv.focus();

theEditorDoc.execCommand("InsertOrderedList")

It seems to all work for me, at present until I get the next nasty surprise from “contentEditable” and “execCommand”

Ps How do I get the first line of my code to lineup with the rest?

IDs are case sensitive. Try MAINCONTENTS instead of MainContents.

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