代码下载地址:http://download.csdn.net/detail/dfg727/7616305

 

1. a.配置tinymce,增加一个insert code按钮
    b.处理显示页面中展开收缩的高亮部分事件

var tinymce_config = function (selector) {
    tinymce.init({
        selector: selector,
        theme: "modern",
        menubar: false,
        plugins: [
            "preview",
            "insertcode code",
            "emoticons textcolor colorpicker "
        ],
        external_plugins: {
            //"insertcode": "plugins/insertcode/plugin.min.js"
        },
        content_css: "CodeHighlighter/CodeHighlighter.css",
        toolbar: "undo redo | bold italic | fontselect fontsizeselect | alignleft aligncenter alignright alignjustify | forecolor backcolor emoticons | insertcode code preview",

        setup: function (editor) {
            editor.addButton('insertcode', {
                image: "/CodeHighlighter/images/insertCode.gif",
                onclick: function () {
                    showDialog(editor);
                }
            });
        }
    });

    function showDialog(editor) {
        var win = editor.windowManager.open({
            title: "Insert code",
            //file: '/InsertCode.aspx',
            width: parseInt(editor.getParam("plugin_preview_width", "550"), 10),
            height: parseInt(editor.getParam("plugin_preview_height", "320"), 10),
            html: '<iframe id="insercode_iframe" src="/CodeHighlighter/insertcode.html" frameborder="0"></iframe>',
            buttons: {
                text: 'Submit',
                onclick: function () {
                    var iframe = $('#insercode_iframe')[0].contentWindow.document;
                    var that = this;
                    var codeText = $("#CodeTextBox", iframe).val().trim();
                    if (codeText == "") {
                        alert("please input the codes");
                        return false;
                    }
                    $.ajax({
                        type: "POST",
                        url: "Highligh.aspx",
                        data: {
                            "Language": $("#LanguageDropDownList", iframe).val(),
                            "IsCollapse": $("#cbOutliningEnabled", iframe)[0].checked,
                            "IsShowLineNumber": $("#cbLineNumberMarginVisible", iframe)[0].checked,
                            "CodeText": $("#CodeTextBox", iframe).val(),
                            "CodeTitle": $("#CodeTitle", iframe).val()
                        },
                        //data: "Id=5&Name=lia5",
                        //dataType: "json",
                        success: function (data) {
                            editor.focus();

                            editor.execCommand('mceInsertContent', false, data);

                            that.parent().parent().close();
                        },
                        error: function () {
                            alert("have error, please contact admin.");
                        }
                    });

                }
            }
        });
    }
}

//显示页面中展开收缩高亮部分
var code_highlight = function () {
    var collapse = function () {
        $(".code_img_closed, .cnblogs_code_collapse").click(function () {
            $(this).hide()
                .siblings(".code_img_closed").hide().end()
                .siblings(".cnblogs_code_collapse").hide().end()
                .siblings(".code_img_opened").show().end()
                .siblings("div[id^=cnblogs_code_open_]").show().end();
        });
        $(".code_img_opened").click(function () {
            $(this).hide()
                .siblings(".code_img_closed").show().end()
                .siblings(".cnblogs_code_collapse").show().end()
                .siblings(".code_img_opened").hide().end()
                .siblings(".cnblogs_code_hide").hide().end();
        });
    };

    var copy = function () {
        $(".cnblogs_code_copy>img").click(function () {
            var $code_open = $(this).parents("div[id^='cnblogs_code_open_']");
            $code_open.hide()
                .siblings("div[id^='cnblogs_code_copy_']").show().end()
                .siblings(".code_img_opened").hide();
        })
    };

    return {
        init: function () {
            collapse();
            copy();
        }
    }
}();
View Code

 

2.在编辑页面中给编辑器初始化为刚刚配置的tinymce_config

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Add.aspx.cs" Inherits="Add" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>    
    <script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
    <script src="scripts/tinymce/js/tinymce/tinymce.min.js"></script>
    <script src="CodeHighlighter/config.js"></script>
    <script type="text/ecmascript">
        $(function () {
            tinymce_config("textarea#elm1");
        });
    </script>
    <style>      

    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 80%"></textarea>
        <a href="javascript:;" onclick="$('#show').html(tinymce.get('elm1').getContent());code_highlight.init();return false;">[Get contents]</a>        
    </div>

    <!--显示编辑器的内容-->
    <link rel="stylesheet" href="/CodeHighlighter/CodeHighlighter.css" />    
    <div id="show"></div>
    </form>
</body>
</html>
View Code

 

3.insert code按钮调用插入页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style>
        div {
            font-size:12px;
            line-height:30px;
        }
        .label-desc {
            padding:10px;
        }
    </style>
</head>
<body>
    <div>
        <label class="label-desc">语言:</label>
        <select name="LanguageDropDownList" id="LanguageDropDownList">
            <option value="Assembly">Assembly</option>
            <option value="BatchFile">BatchFile</option>
            <option selected="selected" value="C#">C#</option>
            <option value="CSS">CSS</option>
            <option value="HTML">HTML</option>
            <option value="INIFile">INIFile</option>
            <option value="Java">Java</option>
            <option value="JScript">JScript</option>
            <option value="Lua">Lua</option>
            <option value="MSIL">MSIL</option>
            <option value="Pascal">Pascal</option>
            <option value="Perl">Perl</option>
            <option value="PHP">PHP</option>
            <option value="PowerShell">PowerShell</option>
            <option value="Python">Python</option>
            <option value="SQL">SQL</option>
            <option value="VB.NET">VB.NET</option>
            <option value="VBScript">VBScript</option>
            <option value="XAML">XAML</option>
            <option value="XML">XML</option>
        </select>
    </div>
    <div>
        <label class="label-desc">选项:</label>
        <label>
            <input type="checkbox" id="cbLineNumberMarginVisible" />显示行号
        </label>
        <label>
            <input type="checkbox" id="cbOutliningEnabled" />全部折叠
        </label>        
        折叠标题 <input id="CodeTitle" type="text" value="view code" /> 
    </div>
    <div>
        <label class="label-desc" style="vertical-align:top;">代码:</label>        
        <textarea id="CodeTextBox" rows="14" cols="55"></textarea>
    </div>
</body>
</html>
View Code

 

4.代码提交到后台,用 ActiproSoftware.CodeHighlighter 进行高亮
前端aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Highligh.aspx.cs" Inherits="Highligh" %>
<%@ Register TagPrefix="CH" Namespace="ActiproSoftware.CodeHighlighter" Assembly="ActiproSoftware.CodeHighlighter.Net20" %>

<CH:CodeHighlighter runat="server" 
                    ID="Highlighter"
    OnPostRender="CodeHighlighter_PostRender" />
View Code

后台aspx.cs

using ActiproSoftware.CodeHighlighter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Highligh : System.Web.UI.Page
{
    private bool IsCollapse = false;
    private string codeTitle = "View Code";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Form["CodeText"] != null && Request.Form["CodeText"].ToString() != "")
            {
                Highlighter.Text = Request.Form["CodeText"].ToString();
            }
            else
            {
                throw new HttpException();
            }

            if (Request.Form["Language"] != null && Request.Form["Language"].ToString() != "")
            {
                Highlighter.LanguageKey = Request.Form["Language"].ToString();
            }
            else
            {
                Highlighter.LanguageKey = "C#";
            }

            if (Request.Form["IsCollapse"] != null && Request.Form["IsCollapse"].ToString() != "")
            {
                IsCollapse = Convert.ToBoolean(Request.Form["IsCollapse"]);
            }

            if (Request.Form["IsShowLineNumber"] != null && Request.Form["IsShowLineNumber"].ToString() != "")
            {
                Highlighter.LineNumberMarginVisible = Convert.ToBoolean(Request.Form["IsShowLineNumber"]);
            }
            else
            {
                Highlighter.LineNumberMarginVisible = false;
            }
            Highlighter.OutliningEnabled = false;

            if (Request.Form["CodeTitle"] != null && Request.Form["CodeTitle"].ToString() != "")
            {
                codeTitle = Request.Form["CodeTitle"].ToString();
            }
        }
    }

    protected void CodeHighlighter_PostRender(object sender, EventArgs e)
    {
        string highligh = ((Highlighter.Output).Substring(117));
        highligh = highligh.Substring(0, highligh.Length - 6);
        string html = string.Format(normalTemplate, highligh);
        if (IsCollapse)
        {
            html = string.Format(collapseTemplate,
                System.Guid.NewGuid().ToString(),
                Highlighter.Text,
                highligh,
                codeTitle
                );
        }
        /*
        var outo = new
        {
            Html = (Highlighter.Output).Substring(117),
            Text = Highlighter.Text
        };*/
        Response.Clear();
        //Response.ContentType = "application/json";
        Response.Write(html);
        Response.End();
    }

    private readonly string normalTemplate = @"
        <div class='cnblogs_code'><pre>{0}</pre></div>";

    private readonly string collapseTemplate = @"
        <div class='cnblogs_code'>            
            <img id='code_img_closed_{0}' class='code_img_closed' 
                src='/CodeHighlighter/Images/ContractedBlock.gif' 
                alt='' 
                style='display: inline;' />
            <span class='cnblogs_code_collapse' style='display: inline;'>{3}</span>
            <img id='code_img_opened_{0}' class='code_img_opened' 
                style='display: none;' 
                src='/CodeHighlighter/Images/ExpandedBlockStart.gif' 
                alt='' />
            <div id='cnblogs_code_open_{0}' class='cnblogs_code_hide'>                
                <div class='cnblogs_code_toolbar'><span class='cnblogs_code_copy'><img src='/CodeHighlighter/Images/copycode.gif' alt='复制代码'/></span></div>
                <pre>{2}</pre>
                <div class='cnblogs_code_toolbar'><span class='cnblogs_code_copy'><img src='/CodeHighlighter/Images/copycode.gif' alt='复制代码'/></span></div>
            </div>
            <div id='cnblogs_code_copy_{0}' class='cnblogs_code_hide'>
                <div>按 Ctrl+C 复制代码</div>
                <textarea style='width: 99%; height: 100px; font-family: 'Courier New'; font-size: 12px; line-height: 1.5;'>{1}</textarea>
                <div>按 Ctrl+C 复制代码</div>
            </div>
        </div>";
}
View Code

点击get contents

点击展开

点击复制图标

 

 

 

 

posted on 2014-07-10 14:17  dfg727  阅读(3754)  评论(7编辑  收藏  举报