text Плагин - текстовыйредактор

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text Плагин - текстовыйредактор相关的知识,希望对你有一定的参考价值。

"use strict";
(function (win, doc, $) {
    debugger;
    var create = function (tagName, props) {
        return $($.extend(doc.createElement(tagName), props));
    };

    $.suitUp = {
        controls: ['italic', 'bold', '|', 'formatblock#<h1>', 'formatblock#<h2>', 'formatblock#<h3>', 'formatblock#<p>', '|', 'fontname', 'link', '|', 'insertimage'],

        commands: {
            createlink: function (callback) {
                callback(win.prompt('URL:', ''));
            },
            fontname: {
                Arial: 'arial',
                Times: 'times'
            },
            insertimage: function (callback, files) {
                if (files.length === 0) return;
                // Только изображения
                var error = false;
                for (var k = 0; k < files.length; k++) {
                    if (!files[k].type.match('image.*')) {
                        error = true;
                    }
                }

                var buttons = {};
                if (error === false) {

                    buttons = {};
                    buttons[_('Загрузить')] = true;
                    buttons[_('Отмена')] = false;
                    $.slPrompt('<div id="file-uploader-thumbs" class="file-uploader-thumbs"></div>', {
                        close: true,
                        title: _('Подтвердите действие'),
                        prefix: 'pre_',
                        buttons: buttons,
                        callback: function (value, message, fields) {},
                        submit: function (value, message, fields) {
                            if (value === true) {
                                $.prompt.closePrompt($('#pre_box'), null, null, null, null);
                                $.loader(_('Загрузка изображения...'));
                                var formData;
                                var deferreds = [];
                                var error = false;
                                for (var i = 0; i < files.length; i++) {
                                    formData = new FormData();
                                    formData.append('qqfile', files[i]);
                                    deferreds.push(
                                        $.ajax({
                                            url: '/File/ajaxUpload',
                                            data: formData,
                                            processData: false,
                                            contentType: false,
                                            type: 'post',
                                            dataType: 'json',
                                            success: function (data) {
                                                bindingsUtil.updateAjaxResponse(data);
                                                if (data.success === true) {
                                                    var filePath = data.user_dir + '/' + data.filename;
                                                    callback('/File/show' + filePath);
                                                } else if (data.error) {
                                                    error = true;
                                                    $.slPrompt(_(data.error), {
                                                        title: _('Ошибка'),
                                                        close: true,
                                                        buttons: _('ОК', true),
                                                        prefix: 'file_err_'
                                                    });
                                                }
                                            }
                                        })
                                    );
                                }
                                $.when.apply($, deferreds).done(function() {
                                    if (error === false) {
                                        $.prompt.closePrompt($('#loadingbox'), null, null, null, null);
                                        // input clear
                                        clearInputFile();

                                    }
                                });
                            } else {
                                // input clear
                                clearInputFile();
                            }
                        },
                        loaded: function () {
                            handleFileSelect(files);
                        }
                    });

                } else {
                    buttons = {};
                    buttons[_('ОК')] = true;
                    $.slPrompt(_('Только изображения, пожалуйста'), {
                        close: true,
                        title: _('Ошибка'),
                        prefix: 'err_',
                        buttons: buttons
                    });
                }

                /**
                 * Рендер превьюшек
                 * @param files
                 */
                function handleFileSelect(files) {
                    for (var i = 0, f; f = files[i]; i++) {
                        var reader = new FileReader();
                        reader.onload = (function (theFile) {
                            return function (e) {
                                var div = document.createElement('div');
                                div.className = 'file-uploader-thumb';
                                div.innerHTML = ['<img class="file-uploader-img" title="', (theFile.name), '" src="', e.target.result, '" />'].join('');
                                document.getElementById('file-uploader-thumbs').insertBefore(div, null);
                            };
                        })(f);
                        // Чтение изображений в виде data URL.
                        reader.readAsDataURL(f);
                    }
                }
                /**
                 * Очистит input от выбранных файлов
                 */
                function clearInputFile() {
                    var inputFile = $('#file-uploader input');
                    $(inputFile).attr('type', '');
                    $(inputFile).attr('type', 'file');
                }
            },
        },

        custom: {
            link: function (textarea, suitUpBlock) {
                return create('a', {
                    className: 'suitup-control',
                    href: '#'
                }).attr({
                    'data-command': 'createlink' // adding same style as for createlink command button
                }).on('click', function () {
                    if (!$.suitUp.hasSelectedNodeParent('a')) {
                        var linkUrl = win.prompt('URL:', 'http://');
                        if (linkUrl !== null) {
                            if (linkUrl.indexOf('http') !== 0) {
                                linkUrl = 'http://' +  linkUrl;
                            }
                            doc.execCommand('createlink', false, 'TEMP_HREF');
                            var a = $('a[href="TEMP_HREF"]');
                            $(a).attr('target', '_blank');
                            $(a).attr('href', linkUrl);
                            if ($(a).html() === 'TEMP_HREF') {
                                $(a).html(linkUrl);
                            }
                        }
                    } else {
                        doc.execCommand('unlink', false, null);
                    }
                    textarea.value = $(suitUpBlock).find('.suitup-editor').html();
                });

            },
        },

        getSelection: function () {
            var range;
            if (win.getSelection) {
                try {
                    range = win.getSelection().getRangeAt(0);
                } catch (e) {
                }
            } else if (doc.selection) {
                range = doc.selection.createRange();
            }
            return range;
        },

        restoreSelection: function (range) {
            var s;
            if (range) {
                if (win.getSelection) {
                    s = win.getSelection();
                    if (s.rangeCount > 0)
                        s.removeAllRanges();
                    s.addRange(range);
                } else if (doc.createRange) {
                    win.getSelection().addRange(range);
                } else if (doc.selection) {
                    range.select();
                }
            }
        },

        getSelectedNode: function () {
            if (doc.selection) {
                return doc.selection.createRange().parentElement();
            } else {
                var selection = win.getSelection();
                if (selection.rangeCount > 0) {
                    return selection.getRangeAt(0).endContainer;
                }
            }
        },

        hasSelectedNodeParent: function (tagName) {
            var node = this.getSelectedNode(),
                has = false;
            tagName = tagName.toUpperCase();
            while (node && node.tagName !== 'BODY') {
                if (node.tagName === tagName) {
                    has = true;
                    break;
                }
                node = node.parentNode;
            }
            return has;
        },
    };

    $.fn.suitUp = function (controls) {
        var suitUp = $.suitUp,
            lastSelectionRange,
            lastSelectionElement,
            commands = $.suitUp.commands,
            custom = $.suitUp.custom,
            getSelection = suitUp.getSelection,
            restoreSelection = suitUp.restoreSelection;

        controls = controls || $.suitUp.controls;

        controls = controls instanceof Array ? controls : Array.prototype.slice.call(arguments); // IE changes the arguments object when one of the arguments is redefined

        return this.each(function () {
            var that = this,
                self = $(this).hide(),
                buttonControls,
                selectControls,
                typeofCommandValue,
                commandValue,
                select,

                mainBlock = create('div', {
                    className: 'suitup'
                }).width(self.width()),

                controlsBlock = create('div', {
                    className: 'suitup-controls'
                }).appendTo(mainBlock),

                containerBlock = create('div', {
                    className: 'suitup-editor',
                    contentEditable: true
                }).keyup(function () {
                    updateTextarea();
                    highlightActiveControls();
                }).focus(function () {
                    lastSelectionElement = this;
                    //document.execCommand('styleWithCSS', null, false);
                }).mouseup(function () {
                    highlightActiveControls();
                })
                    .html(that.value)
                    .height(self.height())
                    .appendTo(mainBlock),

                updateTextarea = function () {
                    that.value = containerBlock.html();
                },

                highlightActiveControls = function () {
                    buttonControls = buttonControls || $('a.suitup-control', controlsBlock);
                    buttonControls
                        .removeClass('active')
                        .each(function () {

                            var self = $(this),
                                command = self.data('command'),
                                value = self.data('value');

                            try {
                                value = value ? value.replace('<', '').replace('>', '') : value; // for formatBlock
                                doc.queryCommandValue(command) === (value || 'true') && self.addClass('active');
                            } catch (e) {}

                            try {
                                doc.queryCommandState(command) && self.addClass('active');
                            } catch (e) {}

                        });

                    selectControls = selectControls || $('select.suitup-control', controlsBlock);
                    selectControls.each(function () {
                        var self = $(this),
                            command = self.data('command'),
                            value = doc.queryCommandValue(command),
                            option = self.children('option').filter(function () {
                                return value && this.value.toLowerCase() === value.toLowerCase();
                            });

                        if (option.length) {
                            this.value = option.val();
                        }
                    });
                };

            for (var splittedControl, i = 0, control = controls[0]; i < controls.length; control = controls[++i]) {
                splittedControl = control.split('#');
                control = splittedControl[0];
                commandValue = splittedControl[1];

                if (control === '|') {
                    create('span', {
                        className: 'suitup-separator'
                    }).appendTo(controlsBlock);

                } else if (control in custom) {
                    custom[control](that, mainBlock[0]).appendTo(controlsBlock);

                } else {
                    commandValue = commandValue || commands[control] || null;
                    typeofCommandValue = typeof commandValue;

                    if (commandValue && typeofCommandValue === 'object') {

                        select = create('select', {
                            className: 'suitup-control'
                        })
                            .attr('data-command', control)
                            .appendTo(controlsBlock)
                            .on('change', {command: control}, function (event) {
                                var command = event.data.command;
                                doc.execCommand(command, null, this.value);
                                updateTextarea();
                            });

                        $.each(commandValue, function (displayName, commandValue) {
                            create('option', {
                                value: commandValue
                            }).html(displayName)
                                .appendTo(select);
                        });

                    } else {

                        // Вставка изображений
                        if (control === 'insertimage') {

                            var a = create('a', {
                                href: '#',
                                className: 'suitup-control'
                            }).attr('data-command', 'insertimage');

                            $(a).appendTo(controlsBlock);

                            var fileUploaderDiv = create('div', {
                                id: 'file-uploader',
                                className: 'file-uploader'
                            });

                            var label = create('label');
                            var input = create('input', {
                                type: 'file',
                                name: 'file[]'
                            }).attr('multiple', true);

                            $(label).append(input);
                            $(fileUploaderDiv).append(label);
                            $(fileUploaderDiv).appendTo(controlsBlock);

                            $(input).on('change', {command: control, value: commandValue, typeofValue: typeofCommandValue}, function(event) {
                                var command = event.data.command,
                                    value = event.data.value,
                                    files = event.target.files;

                                if (lastSelectionElement !== containerBlock[0] || !lastSelectionRange) {
                                    containerBlock.focus();
                                }

                                lastSelectionRange = getSelection();
                                value(function (resultValue) {
                                    lastSelectionElement.focus();
                                    restoreSelection(lastSelectionRange);
                                    doc.execCommand(command, null, resultValue);
                                    updateTextarea();
                                }, files);

                                return false;
                            });

                            $(a).on('click', function() {
                                $('#file-uploader label').trigger('click');
                            });

                        } else {
                            create('a', {
                                href: '#',
                                className: 'suitup-control'
                            })
                                .attr({
                                    'data-command': control,
                                    'data-value': typeofCommandValue === 'function' ? '_DYNAMIC_' : commandValue
                                })
                                .appendTo(controlsBlock)
                                .on('click', {command: control, value: commandValue, typeofValue: typeofCommandValue}, function (event) {
                                    var command = event.data.command,
                                        value = event.data.value,
                                        typeofValue = event.data.typeofValue,
                                        resultValue;

                                    if (lastSelectionElement !== containerBlock[0] || !lastSelectionRange) {
                                        containerBlock.focus();
                                    }

                                    if (typeofValue === 'function') {
                                        lastSelectionRange = getSelection();
                                        value(function (resultValue) {
                                            lastSelectionElement.focus();
                                            restoreSelection(lastSelectionRange);
                                            doc.execCommand(command, null, resultValue);
                                            updateTextarea();
                                        });

                                    } else {
                                        resultValue = value;
                                        doc.execCommand(command, null, resultValue);
                                        updateTextarea();
                                        highlightActiveControls();
                                    }

                                    return false;
                                });
                        }

                    }

                }
            }

            mainBlock.insertBefore(that);

        });


    };
})(window, document, jQuery);
.suitup {}
.suitup-textarea{width: 500px ;height: 200px;}
.suitup-controls {
	display: flex;
	min-height: 30px;
	border: 1px solid #d8d9db;
	-webkit-border-top-left-radius: 5px;
	-webkit-border-top-right-radius: 5px;
	-moz-border-radius-topleft: 5px;
	-moz-border-radius-topright: 5px;
	border-top-left-radius: 5px;
	border-top-right-radius: 5px;
	
	background: #f2f3f8;
	background: -moz-linear-gradient(top,  #f2f3f8 0%, #e7eaef 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f2f3f8), color-stop(100%,#e7eaef));
	background: -webkit-linear-gradient(top,  #f2f3f8 0%,#e7eaef 100%);
	background: -o-linear-gradient(top,  #f2f3f8 0%,#e7eaef 100%);
	background: -ms-linear-gradient(top,  #f2f3f8 0%,#e7eaef 100%);
	background: linear-gradient(to bottom,  #f2f3f8 0%,#e7eaef 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f2f3f8', endColorstr='#e7eaef',GradientType=0 );

}

.suitup-editor {
	padding: 10px;
	box-sizing: border-box;
	border: 1px solid #e7eaef;
	border-top: none;
	overflow: auto;
	font-family: arial;
	background-color: white;
	-webkit-border-bottom-right-radius: 5px;
	-webkit-border-bottom-left-radius: 5px;
	-moz-border-radius-bottomright: 5px;
	-moz-border-radius-bottomleft: 5px;
	border-bottom-right-radius: 5px;
	border-bottom-left-radius: 5px;
}

.suitup-editor li { margin-left: 30px; }

.suitup-separator {
	display: inline-block;
	vertical-align: middle;
	width: 1px;
	height: 30px;
	background: #d8d9db;
	margin: 0 3.5px;
}

.suitup-control {
	display: inline-block;
	vertical-align: middle;
}

a.suitup-control, span.suitup-control {
	height: 16px;
	width: 16px;
	margin: 7px;
}

a.suitup-control {
	background: url(/modules/informing/images/suitup-sprite.png) no-repeat;
}

a.suitup-control.active{ background-color: #e0e0e5; }

select.suitup-control {}

a.suitup-control[data-command="createlink"] {
	background-position: 0 0;
}
a.suitup-control[data-command="justifycenter"] {
	background-position: 0 -16px;
}
a.suitup-control[data-command="justifyfull"] {
	background-position: 0 -32px;
}
a.suitup-control[data-command="justifyright"] {
	background-position: 0 -48px;
}
a.suitup-control[data-command="justifyleft"] {
	background-position: 0 -64px;
}
a.suitup-control[data-command="bold"] {
	background-position: 0 -96px;
}
a.suitup-control[data-command="forecolor"] {
	background-position: 0 -112px;
}
a.suitup-control[data-command="formatblock"][data-value="<h1>"] {
	background-position: 0 -128px;
}
a.suitup-control[data-command="formatblock"][data-value="<h2>"] {
	background-position: 0 -144px;
}
a.suitup-control[data-command="formatblock"][data-value="<h3>"] {
	background-position: 0 -160px;
}
a.suitup-control[data-command="formatblock"][data-value="<h4>"] {
	background-position: 0 -176px;
}
a.suitup-control[data-command="formatblock"][data-value="<h5>"] {
	background-position: 0 -192px;
}
a.suitup-control[data-command="formatblock"][data-value="<h6>"] {
	background-position: 0 -208px;
}
a.suitup-control[data-command="italic"] {
	background-position: 0 -224px;
}
a.suitup-control[data-command="insertorderedlist"] {
	background-position: 0 -240px;
}
a.suitup-control[data-command="insertunorderedlist"] {
	background-position: 0 -256px;
}
a.suitup-control[data-command="strikethrough"] {
	background-position: 0 -272px;
}
a.suitup-control[data-command="subscript"] {
	background-position: 0 -288px;
}
a.suitup-control[data-command="superscript"] {
	background-position: 0 -304px;
}
a.suitup-control[data-command="underline"] {
	background-position: 0 -320px;
}
a.suitup-control[data-command="insertimage"] {
	background-position: 0 -336px;
}
/*
	doesn't work in ie
	a.suitup-control[data-command="decreasefontsize"] {
		background-position: 0 -368px;
	}
	a.suitup-control[data-command="increasefontsize"] {
		background-position: 0 -384px;
	}
*/
a.suitup-control[data-command="formatblock"][data-value="<p>"] {
	background-position: 0 -400px;
}
/*
	doesn't work in ie
	a.suitup-control[data-command="formatBlock"][data-value="<blockquote>"] {
		background-position: 0 -416px;
	}
*/
.file-uploader {
	display: none;
}
.file-uploader input[type="file"]{
	display: none;
}
.file-uploader label {
	padding: 0;
	width: 30px;
}
.file-uploader-thumbs {
	display: flex;
	flex-wrap: wrap;
	flex-direction: row;
	justify-content: center;
	width: 480px;
	margin: auto;
}
.file-uploader-thumb {
	width: 100px;
	margin: 10px;
}
.file-uploader-img {
	width: 100%;
	height: auto;
}
$('.htmleditor').suitUp();
// .htmleditor - это textarea
// Сохранил в \Dropbox\documents\Starliner\suitup
/images/suitup-sprite.png

以上是关于text Плагин - текстовыйредактор的主要内容,如果未能解决你的问题,请参考以下文章

html 选择 - выпадающийсписоксвыделениемцветомродительскойкатегории

php Проверкаестьлифильтрынавигацияпродуктывтекущейкатегории

php Вывестиминимальнуюценуторговыхпредложенийвсписоктоваров

sh Вывестиинформациюотомктоавторикогдаменялисьпервые3строкифайла自述文件

比特币不能购买特斯拉了!今日比特币狂跌背后的原因……

php ОставляетуказанныегруппыполейACFнастраницеуказанныхтерминоввадминке,анаостальныхудаляет。