两种为wangEditor添加拖拽调整高度的方式:CSS3和jQuery UI

wangEditor是一款优秀的Web富文本编辑器,但如果能像KindEditor那样支持拖拽调整高度就更好了。有两种方式可以为wangEditor添加这一功能,这里使用的wangEditor版本为2.1.22。

第一种方式是最简单,也是比较完美的一种方式:为编辑器元素添加值为vertical的resize CSS样式:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生CSS方式</title>
    <meta charset="utf-8" />
    <link href="Content/wangEditor/css/wangEditor.css" rel="stylesheet" />
    <script src="Scripts/jquery-3.1.1.js"></script>
    <script src="Scripts/wangEditor.js"></script>
    <style>
        #editor {
            resize: vertical;
        }
    </style>
</head>
<body>
    <div id="editor"></div>
    <script>
        var editor = new wangEditor("editor");
        editor.create();
    </script>
</body>
</html>

这样,编辑器的右下角就变成了可以拖动的把手(值vertical使其仅可垂直拖动):

使用这种方式,在Chrome里,无法将编辑器的高度拖动到比原始高度更小,而在FireFox里,可以拖动到任意大小。

第二种方式是使用jQuery UI的resizable组件。使用这种方式的优点是可以让编辑器的整个下边框可以拖动,但由于编辑器和resizable组件难以完美结合,导致这种方法略微复杂,并且会导致编辑器的全屏功能无法正常使用。代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jQuery UI方式</title>
    <meta charset="utf-8" />
    <link href="Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="Content/wangEditor/css/wangEditor.css" rel="stylesheet" />
    <script src="Scripts/jquery-3.1.1.js"></script>
    <script src="Scripts/jquery-ui-1.12.1.js"></script>
    <script src="Scripts/wangEditor.js"></script>
</head>
<body>
    <div id="editor"></div>
    <script>
        var editor = new wangEditor("editor");

        // 由于这种方式导致全屏功能异常,所以应该移除全屏按钮
        editor.config.menus = $.grep(editor.config.menus, function (menu) {
            return menu != "fullscreen";
        });

        editor.create();

        // 类为wangEditor-container的元素是wangEditor为编辑器元素包裹的最外层元素,应使其成为resizable组件,而不是包含编辑器文本内容的元素(即ID为editor的div元素
        $(".wangEditor-container").resizable({
            // 只让下边框可以拖动
            handles: "s",
            // 拖动时,不断调整内层编辑器文本区域的高度
            resize: setTextAreaHeight
        });

        // 调整浏览器窗口大小时,也要同时调整编辑器文本区域的高度
        $(window).bind("resize", setTextAreaHeight);

        // 调整编辑器内层文本区域高度的函数,计算方法是编辑器包装元素高度减工具栏高度,再减文本区域的垂直margin和padding之和
        function setTextAreaHeight() {
            $("#editor").height($(".wangEditor-container").height() - $(".wangEditor-menu-container").height() - 20);
        }
    </script>
</body>
</html>

使用这种方式,可以调整到任意高度(无右下角拖拽把手,但鼠标移到下边框时,会呈上下双箭头状):

注:第二种方式未考虑查看源代码区域的高度,所以如果使用第二种方式,还应该隐藏查看源代码按钮,或者同时调整源代码区域的高度。

posted @ 2016-12-14 15:01  zhu'sDevlog  阅读(6115)  评论(2编辑  收藏  举报