js富文本简单编写练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .editable{
             200px;
            height: 200px;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <div class="editable" id="richedit" contenteditable="true"></div>
    <input type="button" id="btn1" value="变红">
    <input type="button" id="btn2" value="变粗">
    <script>
            var btn1 = document.getElementById("btn1");
            var btn2 = document.getElementById("btn2");

            btn1.onclick = function(){
                document.execCommand("forecolor",false,"#ff0000");
            }
            btn2.onclick = function(){
                document.execCommand("bold",false,null);
            }
    </script>
</body>
</html>

效果:

还可以继续编写其他富文本功能,方法类似

原文地址:https://www.cnblogs.com/qianbin/p/10106189.html