<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script language="javascript" type="text/javascript"> //初始化編輯器 function init() { var ifr = document.getElementById("editor"); var doc = ifr.contentDocument || ifr.contentWindow.document; // W3C || IE doc.designMode = "on"; doc.contentEditable = true; doc.write('<html><head><style>body{margin:3px;word - wrap:break-word;word -break:break-all;}</style ></head><body>helloworld!</body></html>'); alert(doc.body.innerHTML); } //設置選定的文本爲粗體/正常 function setBold() { var win = document.getElementById("editor").contentWindow; win.document.execCommand("Bold", false, null); win.focus(); } </script> <p> <input type="button" id="bBtn" value="B" style="font-weight:bold" onclick="setBold();"/> </p> <p> <iframe id="editor" width="600px" height="400px" style="border:solid 1px;"></iframe> </p> <script type="text/javascript"> init(); </script> </body> </html>
參考博客:http://blog.csdn.net/yelbosh/article/details/7693236javascript