Using contentEditable in Firefox: 'bold' renders correctly, but html code is incorrect

六月ゝ 毕业季﹏ 提交于 2019-12-13 19:59:10

问题


I'm trying to write a wysiwyg editor using a contentEditable div, and am having trouble in Firefox when dealing with bold (and italic).

When all text in the div is selected, execCommand('bold') works in the div, but when I try to grab the HTML of that content, the HTML does not reveal any formatting.

To see what I mean, please try running the following HTML code in Firefox 5:

<script type="text/javascript">
window.onload = function () {

    var output = document.getElementById('output');
    var input = document.getElementById('input');

}
</script>
<body>
<button onClick="execCommand('bold', false, null);output.value=input.innerHTML;">Bold</button>
<div style="width: 300px; border: 1px solid #000000;">
<div id="input" contenteditable="true">Some editable text</div>
</div>
<textarea id="output"></textarea>
</body>
</html>

Please try the following:

  • Select the word "Some" only. Click the Bold button. This will make the text bold, as expected. The HTML output uses <span style="font-weight:bold;"> to bold the word, which is somewhat unfortunate (it's <b> in Safari, Chrome), but nonetheless does the job.
  • Select the entire phrase "Some editable text" (either manually or using CTRL-A). Click the Bold button. While the contentEditable text is bold, as expected, the HTML output does not have the bold formatting applied.

Any ideas on what could be causing these problems and how to work around them would be greatly appreciated!


回答1:


Here's a jsFiddle for your original code: http://jsfiddle.net/Bv2Ek/

The issue is that Firefox is adding font-weight: bold to the style attribute of the editable <div> element to make all of it bold, which is quite a reasonable thing to do. If you would rather it used <b> or <strong> elements to apply the boldness, you can use the StyleWithCSS command first. Add the following to your script:

function bold() {
    document.execCommand('StyleWithCSS', false, false);
    document.execCommand('bold', false, null);
}

And your button becomes:

<button onClick="bold(); output.value=input.innerHTML;">Bold</button>

jsFiddle example with amended code: http://jsfiddle.net/Bv2Ek/1/




回答2:


If... that's IF using jQuery.

After exec command:

$('b').contents().unwrap().wrap('<strong/>');


来源:https://stackoverflow.com/questions/6963172/using-contenteditable-in-firefox-bold-renders-correctly-but-html-code-is-inc

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