制作最简单的富文本编辑器

2 篇文章 0 订阅

1、借助HTML DOM的 contentEditable 属性
(描述元素的内容是否可编辑)来让div内容可编辑

2、document的execCommand 方法
该方法允许运行命令来操纵可编辑内容区域的元素。当使用contentEditable时,调用 execCommand() 将影响当前活动的可编辑元素。如何使用可以查看execCommandMDN对应的文档说明

以下为富文本编辑器完整代码:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>富文本编辑器G</title>
        <link href="/static/assets/vendors/bootstrap/css/bootstrap.css" rel="stylesheet">
        <style>
            body{
            padding: 100px 200px;
            }
            #editor {
                height:500px;
                margin: 30px;
            }
        </style>
    </head>
    <body>
        <div id="editparent">
            <!-- 编辑器控制按钮 -->
            <div id='editControls' style='text-align:center; padding:5px;'>                           
                <div class='btn-group'>
                    <a class='btn' data-role='bold' href='#'><b>Bold</b></a>
                    <a class='btn' data-role='italic' href='#'><em>Italic</em></a>
                    <a class='btn' data-role='underline' href='#'><u><b>U</b></u></a>
                    <a class='btn' data-role='strikeThrough' href='#'><strike>abc</strike></a>
                </div>
            </div>
            <!-- 编辑器可输入内容处 -->
            <div id='editor' class='form-control'  contenteditable>
                <h3>在这里输入内容</h3>
            </div>
        </div>
        <script src="/static/assets/vendors/jquery/jquery.js"></script>
        <script>
            $(function() {
                $('#editControls a').click(function(e) {
                    document.execCommand($(this).data('role'), false, null);                  
                })
            });
        </script>
    </body>
</html>

在浏览器中界面显示:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值