`
zuroc
  • 浏览: 1309983 次
  • 性别: Icon_minigender_1
  • 来自: 江苏
社区版块
存档分类
最新评论

jquery.wysiwyg.js

阅读更多
http://code.google.com/p/jwysiwyg/

做些小改动
(function( $ )
{
    $.fn.document = function()
    {
        var element = this[0];

        if ( element.nodeName.toLowerCase() == 'iframe' )
            return element.contentWindow.document;
            /*
            return ( $.browser.msie )
                ? document.frames[element.id].document
                : element.contentWindow.document // contentDocument;
             */
        else
            return $(this);
    };

    $.fn.documentSelection = function()
    {
        var element = this[0];

        if ( element.contentWindow.document.selection )
            return element.contentWindow.document.selection.createRange().text;
        else
            return element.contentWindow.getSelection().toString();
    };

    $.fn.wysiwyg = function( options )
    {
        if ( arguments.length > 0 && arguments[0].constructor == String )
        {
            var action = arguments[0].toString();
            var params = [];

            for ( var i = 1; i < arguments.length; i++ )
                params[i - 1] = arguments[i];

            if ( action in Wysiwyg )
            {   var r;
                this.each(function()
                {
                    $.data(this, 'wysiwyg')
                     .designMode();

                    r=Wysiwyg[action].apply(this, params);
                });
                if(r!==undefined)return r;
            }
            return this;
        }

        var controls = {};

        /**
         * If the user set custom controls, we catch it, and merge with the
         * defaults controls later.
         */
        if ( options && options.controls )
        {
            var controls = options.controls;
            delete options.controls;
        }

        var options = $.extend({
            html : '<'+'?xml version="1.0" encoding="UTF-8"?'+'><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">STYLE_SHEET</head><body>INITIAL_CONTENT</body></html>',
            css  : {},

            debug        : false,

            autoSave     : true,  // http://code.google.com/p/jwysiwyg/issues/detail?id=11
            rmUnwantedBr : true,  // http://code.google.com/p/jwysiwyg/issues/detail?id=15
            brIE         : true,

            controls : {},
            messages : {}
        }, options);

        options.messages = $.extend(true, options.messages, Wysiwyg.MSGS_EN);
        options.controls = $.extend(true, options.controls, Wysiwyg.TOOLBAR);

        for ( var control in controls )
        {
            if ( control in options.controls )
                $.extend(options.controls[control], controls[control]);
            else
                options.controls[control] = controls[control];
        }

        // not break the chain
        return this.each(function()
        {
            Wysiwyg(this, options);
        });
    };

    function Wysiwyg( element, options )
    {
        return this instanceof Wysiwyg
            ? this.init(element, options)
            : new Wysiwyg(element, options);
    }

    $.extend(Wysiwyg, {
        insertImage : function( szURL, attributes )
        {
            var self = $.data(this, 'wysiwyg');

            if ( self.constructor == Wysiwyg && szURL && szURL.length > 0 )
            {
                if ( attributes )
                {
                    self.editorDoc.execCommand('insertImage', false, '#jwysiwyg#');
                    var img = self.getElementByAttributeValue('img', 'src', '#jwysiwyg#');

                    if ( img )
                    {
                        img.src = szURL;

                        for ( var attribute in attributes )
                        {
                            img.setAttribute(attribute, attributes[attribute]);
                        }
                    }
                }
                else
                {
                    self.editorDoc.execCommand('insertImage', false, szURL);
                }
            }
        },

        createLink : function( szURL )
        {
            var self = $.data(this, 'wysiwyg');

            if ( self.constructor == Wysiwyg && szURL && szURL.length > 0 )
            {
                var selection = $(self.editor).documentSelection();

                if ( selection.length > 0 )
                {
                    self.editorDoc.execCommand('unlink', false, []);
                    self.editorDoc.execCommand('createLink', false, szURL);
                }
                else if ( self.options.messages.nonSelection )
                    alert(self.options.messages.nonSelection);
            }
        },
        getContent : function (newContent){
            var self = $.data(this, 'wysiwyg');
            return self.getContent()
        },
        setContent : function( newContent )
        {
            var self = $.data(this, 'wysiwyg');
                self.setContent( newContent );
                self.saveContent();
        },

        clear : function()
        {
            var self = $.data(this, 'wysiwyg');
                self.setContent('');
                self.saveContent();
        },

        MSGS_EN : {
            nonSelection : 'select the text you wish to link'
        },

        TOOLBAR : {
            bold          : { visible : true, tags : ['b', 'strong'], css : { fontWeight : 'bold' } },
            italic        : { visible : true, tags : ['i', 'em'], css : { fontStyle : 'italic' } },
            strikeThrough : { visible : true, tags : ['s', 'strike'], css : { textDecoration : 'line-through' } },
            underline     : { visible : true, tags : ['u'], css : { textDecoration : 'underline' } },

            separator00 : { visible : false, separator : true },

            justifyLeft   : { visible : true, css : { textAlign : 'left' } },
            justifyCenter : { visible : true, tags : ['center'], css : { textAlign : 'center' } },
            justifyRight  : { visible : true, css : { textAlign : 'right' } },
            justifyFull   : { visible : false, css : { textAlign : 'justify' } },

            separator01 : { visible : false, separator : true },

            indent  : { visible : false },
            outdent : { visible : false },

            separator02 : { visible : false, separator : true },

            subscript   : { visible : false, tags : ['sub'] },
            superscript : { visible : false, tags : ['sup'] },

            separator03 : { visible : false, separator : true },

            undo : { visible : false },
            redo : { visible : false },

            separator04 : { visible : false, separator : true },

            insertOrderedList    : { visible : false, tags : ['ol'] },
            insertUnorderedList  : { visible : false, tags : ['ul'] },
            insertHorizontalRule : { visible : false, tags : ['hr'] },

            separator05 : { separator : true },

            createLink : {
                visible : true,
                exec    : function()
                {
                    var selection = $(this.editor).documentSelection();

                    if ( selection.length > 0 )
                    {
                        if ( $.browser.msie )
                            this.editorDoc.execCommand('createLink', true, null);
                        else
                        {
                            var szURL = prompt('URL', 'http://');

                            if ( szURL && szURL.length > 0 )
                            {
                                this.editorDoc.execCommand('unlink', false, []);
                                this.editorDoc.execCommand('createLink', false, szURL);
                            }
                        }
                    }
                    else if ( this.options.messages.nonSelection )
                        alert(this.options.messages.nonSelection);
                },

                tags : ['a']
            },

            insertImage : {
                visible : true,
                exec    : function()
                {
                    if ( $.browser.msie )
                        this.editorDoc.execCommand('insertImage', true, null);
                    else
                    {
                        var szURL = prompt('URL', 'http://');

                        if ( szURL && szURL.length > 0 )
                            this.editorDoc.execCommand('insertImage', false, szURL);
                    }
                },

                tags : ['img']
            },

            separator06 : { separator : true ,visible : false},

            h1mozilla : { visible : false && $.browser.mozilla, className : 'h1', command : 'heading', arguments : ['h1'], tags : ['h1'] },
            h2mozilla : { visible : false && $.browser.mozilla, className : 'h2', command : 'heading', arguments : ['h2'], tags : ['h2'] },
            h3mozilla : { visible : false && $.browser.mozilla, className : 'h3', command : 'heading', arguments : ['h3'], tags : ['h3'] },

            h1 : { visible : false && !( $.browser.mozilla ), className : 'h1', command : 'formatBlock', arguments : ['Heading 1'], tags : ['h1'] },
            h2 : { visible : false && !( $.browser.mozilla ), className : 'h2', command : 'formatBlock', arguments : ['Heading 2'], tags : ['h2'] },
            h3 : { visible : false && !( $.browser.mozilla ), className : 'h3', command : 'formatBlock', arguments : ['Heading 3'], tags : ['h3'] },

            separator07 : { visible : false, separator : true },

            cut   : { visible : false },
            copy  : { visible : false },
            paste : { visible : false },

            separator08 : { separator : true && !( $.browser.msie ) },

            increaseFontSize : { visible : true ,
                exec    : function(){
                    /*
Browser font size 1 -> Safari: 10 px (Actual font size: 8 px)
Browser font size 2 -> Safari: 13 px (Actual font size: 10 px)
Browser font size 3 -> Safari: 16 px (Actual font size: 12 px)
Browser font size 4 -> Safari: 18 px (Actual font size: 14 px)
Browser font size 5 -> Safari: 24 px (Actual font size: 18 px)
Browser font size 6 -> Safari: 32 px (Actual font size: 24 px)
Browser font size 7 -> Safari: 48 px (Actual font size: 36 px)
                    */ 
                    if($.browser.mozilla){
                        this.editorDoc.execCommand('increasefontsize',false,[]);
                    }else{
                        var sf = {
                            10:1,13:2,16:3,18:4,24:5,32:6,48:7
                        }
                        var font_size = parseInt(this.editorDoc.queryCommandValue('FontSize'));
                        if(font_size>7)font_size=sf[font_size];
                        if(font_size&&font_size<7){
                            this.editorDoc.execCommand('FontSize',false,font_size+1);
                        }
                       
                    }
                }
            },
            decreaseFontSize : { visible : true && !( $.browser.msie ), tags : ['small'] },

            separator09 : { separator : true },

            html : {
                visible : false,
                exec    : function()
                {
                    if ( this.viewHTML )
                    {
                        this.setContent( $(this.original).val() );
                        $(this.original).hide();
                    }
                    else
                    {
                        this.saveContent();
                        $(this.original).show();
                    }

                    this.viewHTML = !( this.viewHTML );
                }
            },

            removeFormat : {
                visible : true,
                exec    : function()
                {
                    this.editorDoc.execCommand('removeFormat', false, []);
                    this.editorDoc.execCommand('unlink', false, []);
                }
            }
        }
    });

    $.extend(Wysiwyg.prototype,
    {
        original : null,
        options  : {},

        element  : null,
        editor   : null,

        init : function( element, options )
        {
            var self = this;

            this.editor = element;
            this.options = options || {};

            $.data(element, 'wysiwyg', this);

            var newX = element.width || element.clientWidth;
            var newY = element.height || element.clientHeight;

            if ( element.nodeName.toLowerCase() == 'textarea' )
            {
                this.original = element;

                if ( newX == 0 && element.cols )
                    newX = ( element.cols * 8 ) + 21;

                if ( newY == 0 && element.rows )
                    newY = ( element.rows * 16 ) + 16;

                var editor = this.editor = $('<iframe></iframe>').css({
                    minHeight : ( newY - 6 ).toString() + 'px',
                    width     : ( newX - 8 ).toString() + 'px'
                }).attr('id', $(element).attr('id') + 'IFrame');

                if ( $.browser.msie )
                {
                    this.editor
                        .css('height', ( newY ).toString() + 'px');

                    /**
                    var editor = $('<span></span>').css({
                        width     : ( newX - 6 ).toString() + 'px',
                        height    : ( newY - 8 ).toString() + 'px'
                    }).attr('id', $(element).attr('id') + 'IFrame');

                    editor.outerHTML = this.editor.outerHTML;
                     */
                }
            }

            var panel = this.panel = $('<ul></ul>').addClass('panel');

            this.appendControls();
            this.element = $('<div></div>').css({
                width : ( newX > 0 ) ? ( newX ).toString() + 'px' : '100%'
            }).addClass('wysiwyg')
              .append(panel)
              .append( $('<div><!-- --></div>').css({ clear : 'both' }) )
              .append(editor);

            $(element)
            // .css('display', 'none')
            .hide()
            .before(this.element);

            this.viewHTML = false;

            this.initialHeight = newY - 8;

            /**
             * @link http://code.google.com/p/jwysiwyg/issues/detail?id=52
             */
            this.initialContent = $(element).val();

            this.initFrame();

            if ( this.initialContent.length == 0 )
                this.setContent('');

            if ( this.options.autoSave )
                $('form').submit(function() { self.saveContent(); });

            $('form').bind('reset', function()
            {
                self.setContent( self.initialContent );
                self.saveContent();
            });
        },

        initFrame : function()
        {
            var self = this;
            var style = '';

            /**
             * @link http://code.google.com/p/jwysiwyg/issues/detail?id=14
             */
            if ( this.options.css && this.options.css.constructor == String )
                style = '<link rel="stylesheet" type="text/css" media="screen" href="' + this.options.css + '" />';

            this.editorDoc = $(this.editor).document();
            this.editorDoc_designMode = false;

            try {
                this.editorDoc.designMode = 'on';
                this.editorDoc_designMode = true;
            } catch ( e ) {
                // Will fail on Gecko if the editor is placed in an hidden container element
                // The design mode will be set ones the editor is focused

                $(this.editorDoc).focus(function()
                {
                    self.designMode();
                });
            }

            this.editorDoc.open();
            this.editorDoc.write(
                this.options.html
                    .replace(/INITIAL_CONTENT/, this.initialContent)
                    .replace(/STYLE_SHEET/, style)
            );
            this.editorDoc.close();
            this.editorDoc.contentEditable = 'true';

            if ( $.browser.msie )
            {
                /**
                 * Remove the horrible border it has on IE.
                 */
                setTimeout(function() { $(self.editorDoc.body).css('border', 'none'); }, 0);
            }

            $(this.editorDoc).click(function( event )
            {
                self.checkTargets( event.target ? event.target : event.srcElement);
            });

            /**
             * @link http://code.google.com/p/jwysiwyg/issues/detail?id=20
             */
            $(this.original).focus(function()
            {
                $(self.editorDoc.body).focus();
            });

            if ( this.options.autoSave )
            {
                /**
                 * @link http://code.google.com/p/jwysiwyg/issues/detail?id=11
                 */
                $(this.editorDoc).keydown(function() { self.saveContent(); })
                                 .keyup(function() { self.saveContent(); })
                                 .mousedown(function() { self.saveContent(); });
            }

            if ( this.options.css )
            {
                setTimeout(function()
                {
                    if ( self.options.css.constructor == String )
                    {
                        /**
                         * $(self.editorDoc)
                         * .find('head')
                         * .append(
                         *     $('<link rel="stylesheet" type="text/css" media="screen" />')
                         *     .attr('href', self.options.css)
                         * );
                         */
                    }
                    else
                        $(self.editorDoc).find('body').css(self.options.css);
                }, 0);
            }

            $(this.editorDoc).keydown(function( event )
            {
                if ( $.browser.msie && self.options.brIE && event.keyCode == 13 )
                {
                    var rng = self.getRange();
                        rng.pasteHTML('<br />');
                        rng.collapse(false);
                        rng.select();

    return false;
                }
            });
        },

        designMode : function()
        {
            if ( !( this.editorDoc_designMode ) )
            {
                try {
                    this.editorDoc.designMode = 'on';
                    this.editorDoc_designMode = true;
                } catch ( e ) {}
            }
        },

        getSelection : function()
        {
            return ( window.getSelection ) ? window.getSelection() : document.selection;
        },

        getRange : function()
        {
            var selection = this.getSelection();

            if ( !( selection ) )
                return null;

            return ( selection.rangeCount > 0 ) ? selection.getRangeAt(0) : selection.createRange();
        },

        getContent : function()
        {
            return $( $(this.editor).document() ).find('body').html();
        },

        setContent : function( newContent )
        {
            $( $(this.editor).document() ).find('body').html(newContent);
        },

        saveContent : function()
        {
            if ( this.original )
            {
                var content = this.getContent();

                if ( this.options.rmUnwantedBr )
                    content = ( content.substr(-4) == '<br>' ) ? content.substr(0, content.length - 4) : content;

                $(this.original).val(content);
            }
        },

        appendMenu : function( cmd, args, className, fn )
        {
            var self = this;
            var args = args || [];

            $('<li></li>').append(
                $('<a><!-- --></a>').addClass(className || cmd)
            ).mousedown(function() {
                if ( fn ) fn.apply(self); else self.editorDoc.execCommand(cmd, false, args);
                if ( self.options.autoSave ) self.saveContent();
            }).appendTo( this.panel );
        },

        appendMenuSeparator : function()
        {
            $('<li class="separator"></li>').appendTo( this.panel );
        },

        appendControls : function()
        {
            for ( var name in this.options.controls )
            {
                var control = this.options.controls[name];

                if ( control.separator )
                {
                    if ( control.visible !== false )
                        this.appendMenuSeparator();
                }
                else if ( control.visible )
                {
                    this.appendMenu(
                        control.command || name, control.arguments || [],
                        control.className || control.command || name || 'empty', control.exec
                    );
                }
            }
        },

        checkTargets : function( element )
        {
            for ( var name in this.options.controls )
            {
                var control = this.options.controls[name];
                var className = control.className || control.command || name || 'empty';

                $('.' + className, this.panel).removeClass('active');

                if ( control.tags )
                {
                    var elm = element;

                    do {
                        if ( elm.nodeType != 1 )
                            break;

                        if ( $.inArray(elm.tagName.toLowerCase(), control.tags) != -1 )
                            $('.' + className, this.panel).addClass('active');
                    } while ( elm = elm.parentNode );
                }

                if ( control.css )
                {
                    var elm = $(element);

                    do {
                        if ( elm[0].nodeType != 1 )
                            break;

                        for ( var cssProperty in control.css )
                            if ( elm.css(cssProperty).toString().toLowerCase() == control.css[cssProperty] )
                                $('.' + className, this.panel).addClass('active');
                    } while ( elm = elm.parent() );
                }
            }
        },

        getElementByAttributeValue : function( tagName, attributeName, attributeValue )
        {
            var elements = this.editorDoc.getElementsByTagName(tagName);

            for ( var i = 0; i < elements.length; i++ )
            {
                var value = elements[i].getAttribute(attributeName);

                if ( $.browser.msie )
                {
                    /** IE add full path, so I check by the last chars. */
                    value = value.substr(value.length - attributeValue.length);
                }

                if ( value == attributeValue )
                    return elements[i];
            }

            return false;
        }
    });
})(jQuery);
分享到:
评论

相关推荐

    所见即所得的jQuery富文本编辑器插件-wysiwyg.js

    jQuery是一个广泛使用的JavaScript库,它简化了DOM操作、事件处理、动画效果等任务,而`wysiwyg.js`则是基于jQuery的一款富文本编辑器插件。这款插件旨在为开发者提供一个轻量级、易于集成和自定义的解决方案。 `...

    jQuery富文本编辑器插件-wysiwyg.js

    **jQuery富文本编辑器插件-wysiwyg.js** 在Web开发中,富文本编辑器是一种常见的组件,它允许用户以类似Word的方式编辑HTML内容。`wysiwyg.js`是一款基于jQuery的富文本编辑器插件,为网页提供了一种高效、功能强大...

    富文本编辑器插件-wysiwyg.js

    `wysiwyg.js`是一款基于jQuery的富文本编辑器插件,它以其高效和稳定性能受到开发者青睐。这款插件的主要目标是提供一个快速、无错误并且对页面其他功能无干扰的编辑体验。 在网页开发中,`&lt;textarea&gt;`元素通常被...

    jQuery wysiwyg 编辑器

    3. **jquery.wysiwyg.js** - 这是编辑器的主要JavaScript文件,包含实现编辑器功能的代码。它提供了诸如文本格式化、插入图片、创建列表等功能,并且处理用户交互,如点击按钮时执行相应的操作。开发者可以通过扩展...

    jQuery文本编辑器插件jWYSIWYG

    在技术实现上,jWYSIWYG利用了jQuery的强大功能,通过JavaScript和CSS实现了丰富的文本格式化选项,如字体、大小、颜色、对齐方式等。同时,它还支持插入图片、链接、表格等复杂元素,满足了用户在网页上创建复杂...

    jquery 文本编辑

    `jquery.wysiwyg.js` 是核心JavaScript文件,包含了实现文本编辑功能的代码。它可能包括了事件监听、DOM操作、富文本处理等功能。该文件通常会定义一个插件,使得可以通过简单的jQuery选择器和方法调用来初始化和...

    jquery 富文本编辑器

    4. **JavaScript文件(jquery.wysiwyg.js)** 这是核心的JavaScript文件,实现了富文本编辑器的逻辑。它包含了对用户输入的监听、事件处理、以及与服务器的交互等功能。通过扩展和自定义这个JS文件,开发者可以增加...

    10个基于jQuery或JavaScript的WYSIWYG 编辑器整理

    在线编辑内容的时候,那些基于 JavaScript 的编辑器帮了我们大忙,这些所见即所得(WYSIWYG)编辑器,给我们提供了类似 Office?的操作体验。如今,任何网站内容管理系统(CMS)和博客系统都需要一个这样的编辑器。...

    jquery.mb.editIt:一个智能,简单的基于WebJavaScript所见即所得HTML编辑器

    `jQuery.mb.editIt`是一个出色的JavaScript库,旨在提供一个既智能又简洁的所见即所得(WYSIWYG)编辑器解决方案。这个编辑器允许用户在网页上直接编辑HTML内容,就像在桌面文本编辑器中一样,无需了解HTML语法,...

    轻量级jQuery文本编辑器插件Froala WYSIWYG Editor

    **轻量级jQuery文本编辑器插件Froala WYSIWYG Editor** Froala WYSIWYG Editor是一款高效、易用且功能丰富的jQuery富文本编辑器,它为Web开发者提供了一个优雅的方式来实现用户界面中的文本编辑功能。这款编辑器以...

    jQuery+Bootstarp富文本编辑器插件summernote.js.zip

    Summernote.js是一款基于jQuery和Bootstrap的富文本编辑器,它以直观的WYSIWYG(所见即所得)界面为用户提供编辑体验。这款编辑器的特点包括: 1. **简洁的用户界面**:Summernote的UI设计符合Bootstrap的风格,...

    jQuery富文本编辑器Notebook

    "jQuery富文本编辑器Notebook"是一个专为创建简洁、整洁且美观的所见即所得(WYSIWYG)编辑器而设计的工具。这款编辑器利用了流行的jQuery库,旨在提供一个用户友好的界面,使得内容创作者可以轻松地进行文字编辑、...

    jQuery WYSIWYG Rich Text Editor v0.4.2.rar

    jQuery WYSIWYG编辑器的核心在于其基于流行的JavaScript库jQuery构建,这使得它能够轻松地与其他jQuery插件和功能协同工作。它的兼容性广泛,覆盖了包括Internet Explorer 6到8,Firefox 3,Opera 9,Safari 4以及...

    jQuery WYSIWYG Rich Text Editor v0.4.2

    在技术实现上,jQuery WYSIWYG Editor是通过jQuery插件的形式存在的,这意味着开发者只需要在项目中引入jQuery库和该编辑器的JavaScript文件,就可以轻松地在HTML元素上应用编辑器功能。通过简单的API调用,开发者...

    RichText:所见即所得编辑器开发为jQuery插件

    要求 (建议v.3 +,v.3.2 +) FontAwesome( / ) src/jquery.richtext.min.js src/richtext.min.css初始化编辑器只需在jQuery('textarea')或jQuery('input')字段上调用.richText() jQuery('textarea')也允许使用...

    wysiwygjs是一款十分强大的所见即所得的jQuery富文本编辑器插件

    wysiwyg.js是一款十分强大的、所见即所得的jQuery富文本编辑器插件。wysiwyg.js富文本编辑器体积小,支持选择、键盘、占位等众多事件。而且该富文本编辑器的兼容性十分好,甚至兼容IE6。

    Jquery编辑器Jwysiwyg

    JQuery编辑器Jwysiwyg是一款轻量级、高效且易于使用的富文本编辑器插件,它基于流行的JavaScript库jQuery构建。这款编辑器旨在为网页内容的创建和编辑提供一个直观的用户界面,类似于常见的Word处理软件,让用户在...

    notebook.js-非常有用的jquery富文本编辑器插件

    `notebook.js`是一款强大的、所见即所得(WYSIWYG)的jQuery富文本编辑器。它为网页内容的创建和编辑提供了一种直观且便捷的方式。当用户直接选择文本时,编辑器会自动弹出一系列编辑选项,如字体样式、字号调整、...

    jquery插件集-web文本编辑器jwysiwyg

    `jWYSIWYG`是一个基于jQuery的轻量级插件,它提供了一个所见即所得(WYSIWYG)的编辑界面,使得用户在网页上可以像使用桌面应用那样进行文本编辑。这款插件以其小巧、易于集成和使用的特点受到开发者的青睐。 **一...

Global site tag (gtag.js) - Google Analytics