何为手写公式,很简单,就是在网页上可以写出数学公式,并能够生成Latex格式的字符串。废话不多说,直接走正题。
一、首先大家可以先去官网了解一下myscript这个插件
官方网站:https://dev.myscript.com/
二、在去它的github上看一下这个项目
GitHub:https://github.com/MyScript/myscript-math-web
三、根据github上的介绍,要下载其插件首先你需要用到这个命令:
bower install myscript-math-web
注意:这里解释一下 bower 是个命令,需要安装node.js 具体什么关系的我就不在这里描述了,下面贴出两个网址自己看吧。
关系:https://segmentfault.com/q/1010000002855012
安装node.js:http://jingyan.baidu.com/article/2d5afd69e243cc85a2e28efa.html
安装Git:http://blog.csdn.net/renfufei/article/details/41647875
提示:别忘了配置环境变量,以及自己Github上的昵称和邮箱别忘了设置。
四、配置好后,执行bower install myscript-math-web 这个命令会在当前的目录下生成对应的myscript的js文件以及各种文件。
文件下载地址:http://pan.baidu.com/s/1i5JiFyt
提示:上面这个是我自己项目用的,已测试没问题。
五、关键代码:
<!doctype html> <html> <head> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> <title>myscript-math-web demo</title> <script src="../../webcomponentsjs/webcomponents-lite.js"></script> <!-- <script src="polymer.js"></script> --> <link rel="import" href="../../polymer/polymer.html"> <script src="../../KaTeX/dist/katex.min.js"></script> <link rel="import" href="../../myscript-common-element/myscript-common-element.html"> <dom-module id="myscript-math-web"> <link rel="stylesheet" href="../../KaTeX/dist/katex.min.css"> <style> :host { display: block; } myscript-common-element { height: 100%; } myscript-common-element.result { height: calc(100% - 100px); } .resultField { font-size: larger; overflow: hidden; text-align: center; min-height: 95px; max-height: 95px; padding-top: 5px; position: relative } .katexcontainer { padding-top: 3px ; margin: 0; position: absolute; top: 50%; left: 50%; margin-right: -50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } </style> <template> <div id="resultField" class="resultField" hidden="[[ hideresult ]]"><div class="katexcontainer"></div></div> <myscript-common-element host="[[ host ]]" protocol="[[ protocol ]]" type="MATH" applicationkey="[[ applicationkey ]]" hmackey="[[ hmackey ]]" timeout="[[ timeout ]]" ssl="[[ ssl ]]" hidebuttons="[[ hidebuttons ]]" mathparameters="[[ _mathParameters ]]" canundo="{{ canundo }}" canredo="{{ canredo }}" canclear="{{ canclear }}" on-changed="_onChanged" on-success="_onSuccess" on-error="_onError"> </myscript-common-element> </template> </dom-module> <script> var myresult; Polymer({ is: 'myscript-math-web', properties: { protocol: { type: String, value: MyScript.Protocol.WS }, host: { type: String, value: 'cloud.myscript.com' }, timeout: { type: Number, value: 2000 }, applicationkey: { type: String }, hmackey: { type: String }, canundo: { type: Boolean, notify: true, value: false }, canredo: { type: Boolean, notify: true, value: false }, canclear: { type: Boolean, notify: true, value: false }, hidebuttons: { type: Boolean, value: false }, hideresult: { type: Boolean, value: false, observer: '_hideresultChanged' }, resulttypes: { type: Array, value: [] }, _mathParameters: { type: Object, computed: '_computeMathParameters(resulttypes)' }, result: { type: Object, notify: true }, ssl: { type: Boolean, value: true } }, _clear: function () { this._myscriptCommonElement.clear(); this.fire('myscript-math-web-delete'); }, _undo: function () { this._myscriptCommonElement.undo(); }, _redo: function () { this._myscriptCommonElement.redo(); }, delete: function () { this._clear(); }, undo: function () { this._undo(); }, redo: function () { this._redo(); }, getStats: function () { if (this._myscriptCommonElement) { return this._myscriptCommonElement.getStats(); } }, _onChanged: function (e) { this.fire(e.type, e.detail); }, _onSuccess: function (e) { this.result = {}; if (e.detail.getDocument && e.detail.getDocument().getResultElements().length > 0) { var resultElements = e.detail.getDocument().getResultElements(); for (var res in resultElements) { this.result[resultElements[res].getType()] = resultElements[res].getValue(); } } var resultField = this.querySelector('.katexcontainer'); if (Object.keys(this.result).length !== 0) { if (this.result.hasOwnProperty('LATEX')) { try { katex.render(this._cleanLatexResult(this.result.LATEX), resultField); } catch (e) { resultField.innerHTML = "<span>"+this._cleanLatexResult(this.result.LATEX)+"</span>"; } } else { resultField.innerHTML = "<span>No LaTeX mathematic expression return to the result. Check your resulttypes attribut.</span>"; } } else { resultField.innerHTML = ""; } this.fire('myscript-math-web-result', this.result); myresult=this.result; }, _onError: function (e) { this.fire(e.type, e.detail); }, ready: function () { this._myscriptCommonElement = this.querySelector('myscript-common-element'); this._hideresultChanged(this.hideresult); }, _computeMathParameters: function (resulttypes) { var parameters = new MyScript.MathParameter(); parameters.setResultTypes(resulttypes); return parameters; }, _cleanLatexResult: function (latex) { return latex .replace("\overrightarrow", "\vec") .replace("\llbracket", "\lbracket") .replace("\rrbracket", "\rbracket") .replace("\widehat", "\hat") .replace(new RegExp("(align.{1})", "g"), "aligned"); }, _hideresultChanged: function (hideresult) { if (this._myscriptCommonElement) { if (hideresult) { this._myscriptCommonElement.classList.remove('result'); } else { this._myscriptCommonElement.classList.add('result'); } } } }); //保存函数 function saveFn(){ CloseWindow(myresult); } //关闭函数 function closeFn(){ CloseWindow("close"); } // 关闭弹出窗口 function CloseWindow(action) { if (window.CloseOwnerWindow) { return window.CloseOwnerWindow(action); } else { window.close(); } } function mouseOver(e) { e.src= "finish_show.png"; } function mouseOut(e) { e.src= "finish.png"; } function mouseOver1(e) { e.src= "close_show.png"; } function mouseOut1(e) { e.src= "close.png"; } </script> </head> <style> body { margin: 0; height: 100vh; } myscript-math-web { height: 100%; } .myimg{ cursor:pointer; margin-top: 4px; } </style> <body touch-action="none" unresolved> <template id="app" is="dom-bind"> <myscript-math-web host="webdemoapi.myscript.com" applicationkey="22eda92c-10af-40d8-abea-fd4093c17d81" hmackey="a1fa759f-b3ce-4091-9fd4-d34bb870c601"> </myscript-math-web> </template> <div align="center" style="position:fixed;bottom:0;height:50px;100%;background:url(icon.png) repeat-x 0 0 ;_position:absolute;_margin-top:expression(this.style.pixelHeight+document.documentElement.scrollTop);z-index: 3;"> <img src="finish.png" onmouseover="mouseOver(this)" onmouseout="mouseOut(this)" title="完成" class="myimg" onclick="saveFn()" /> <img src="close.png" onmouseover="mouseOver1(this)" onmouseout="mouseOut1(this)" title="关闭" class="myimg" onclick="closeFn()" /> </div> </body> </html>
就在四点中文件夹下bower_componentsmyscript-math-webdemoaa.html
六、将获取到的latex格式的字符串如何转化成图片呢?
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <% String title = "作业模板"; // 标题 %> <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%> <c:set var="ctx" value="${pageContext.request.contextPath}" /> <html> <head> <!-- ueditor编辑器使用的js文件 --> <script type="text/javascript" charset="utf-8" src="${ctx}/scripts/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="${ctx}/scripts/ueditor/ueditor.all.js"> </script> <script type="text/javascript" charset="utf-8" src="${ctx}/scripts/ueditor/lang/zh-cn/zh-cn.js"></script> <script type="text/javascript" src="${ctx}/scripts/mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>作业模板</title> <style type="text/css"> .tple_textarea { float: left; margin-left: 50px; } .tple_textarea textarea { 800px; height: 170px; } .tple_que { 80%; height: 200px; margin: 40px 0 0 20px; } .tple_que>img { float: left; } .tple_choose { height: 50px; margin-top: 20px; } .tple_choose_ { margin: 6px 0 0 70px; font-family: 黑体; font-size: 18px; color: #28C1A2; float: left; color: #28C1A2; } .tple_type div { float: left; } .tple_type_bt { 66px; height: 30px; margin-left: 20px; border: none; font-family: 黑体; font-size: 16px; outline: 0; margin-left: 20px; -moz-border-radius: 8px; border-radius: 8px; outline: 0; } .tple_type_bt_nochecked { background-color: #FFF; color: #7A7A7A; } .tple_type_bt_checked { background-color: #28C1A2; color: #FFF; } .tple_select { margin: 0px 0px 0px 62px; } .tple_fillin_num { 100px; height: 30px; border: 2px solid #28C1A2; float: right; outline: 0; } .tple_fillin_num_ { float: right; margin: 5px 8px 0 0; font-size: 16px; font-family: 黑体; font-size: 16px; } .tple_ans_ { margin: 15px 0 0 70px; font-family: 黑体; font-size: 18px; color: #28C1A2; float: left; } .tple_answer form>input { 23px; height: 20px; margin: 15px 0 0 40px; } .container label { position: relative; left: 6px; bottom: 3px; font-size: 20px; font-family: 黑体; } .tple_fillin_item { 90%; margin-left: 7%; height: 50px; float: left; } .tple_fillin_empty { 70px; float: left; margin-left: 5px; border: none; text-align: center; border-bottom: solid #000 1px; outline: 0; color: #797979; font-size: 12px; } .tple_fillin_number { 800px; } .tple_fillin_number { 50px; text-align: center; border: none; float: left; } tple_fillin_bt { margin: 10px 0 0 10px; float: left; } .tple_add { 22px; height: 22px; margin-left: 5px; border: none; outline: 0; background: url(/cfs/image/images/homeworktemplate_fillin_add.png) no-repeat; } .tple_minus { 22px; height: 22px; margin-left: 5px; border: none; outline: 0; background: url(/cfs/image/images/homeworktemplate_fillin_minus.png) no-repeat; } .tple_text { margin: 50px 0 40px -35px; } .tple_button { 500px; height: 45px; margin-top: 120px; } .tple_sub { 160px; height: 45px; border: none; outline: 0; font-family: 黑体; font-size: 20px; color: #FFF; float: left; margin-bottom: 20px; } .tple_ctuadd { margin-left: 100px; background-color: #28C1A2; } .tple_sas { margin-left: 40px; background-color: #F1C46F; } .mini-panel-border{ border: none; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; } .mini-window .mini-panel-header { border:none; color: #FFF; background: #28C1A2; } .mini-panel-viewport{ border: none; } .mini-tools-close{ /* background: url(images/tools/close.gif) no-repeat 50% 1px; */ } .mini-messagebox-content{ color: #797979; } .mini-messagebox-content>div>input { padding-left: 5px; border: #28C1A2 solid 1px; outline: none; } .mini-button, a.mini-button { border:none; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; background: #28C1A2; color: #FFF; } body a:hover.mini-button{ border: none; background: #28C1A2; filter:alpha(opacity=50); -moz-opacity:0.5; opacity:0.5; } .side-bar a,.chat-tips i {background: url(${ctx}/image/images/right_bg.png) no-repeat;} .side-bar { 66px;position: fixed;bottom: 20px;right: 25px;font-size: 0;line-height: 0;z-index: 1003;} .side-bar a { 66px;height: 66px;display: inline-block;background-color: #ddd;margin-bottom: 2px;} .side-bar a:hover {background-color: #669fdd;} .side-bar .icon-qq {background-position: 0 -62px;} .side-bar .icon-chat {background-position: 0 -130px;position: relative;} .side-bar .icon-blog {background-position: 0 -198px;} .side-bar .icon-mail {background-position: 0 -266px;} .side-bar .icon-chat:hover .chat-tips {display: block;} .chat-tips {padding: 20px;border: 1px solid #d1d2d6;position: absolute;right: 78px;top: -55px;background-color: #fff;display: none;} .chat-tips i { 9px;height: 16px;display: inline-block;position: absolute;right: -9px;top: 80px;background-position:-88px -350px;} .chat-tips img { 138px;height: 138px;} .zz_bg{display: none; position: absolute; top: 0%; left: 0%; 100%; height: 100%;z-index: 1001;overflow:hidden; } .zz_show{display: none; position: absolute; top: 12%; left: 100%; 60%; height: 75%; padding: 8px; border: 3px solid #28C1A2; background-color: white; z-index:1002; overflow: auto; padding: 0px;} .ques_bg{color:#797979;font-size: 16px; border-bottom: 1px solid #EBEBEB;padding: 5px;background-color:white;} .ques_tx{color:#50C2A7;} .ques_font{color:#EE4000;} .ques_ckda{font-size:20px;} </style> </head> <body> <div class="container" id="container"> <div class="iframe_header"> <div class="ifram_header_icon"> <img src="/cfs/image/images/new_homework.png"> </div> <div class="ifram_header_text"><%=title%></div> <button id="tple_back" class="iframe_header_back"></button> </div> <div class="tple_que"> <div class="tple_textarea"> <!-- <textarea id="tple_stem_text">11111111</textarea> --> <script id="tple_stem_text" type="text/plain" style="700px;height:150px;"></script> </div> </div> <div class="tple_choose"> <nobr class="tple_choose_">题型</nobr> <div class="tple_type"> <div> <button class="tple_type_bt tple_type_bt_nochecked" value="tple_single">单选题</button> <button class="tple_type_bt tple_type_bt_nochecked" value="tple_many">多选题</button> <button class="tple_type_bt tple_type_bt_nochecked" value="tple_judge">判断题</button> <button class="tple_type_bt tple_type_bt_nochecked" value="tple_fillin">填空题</button> <button class="tple_type_bt tple_type_bt_nochecked" value="tple_text">写作题</button> </div> <div class="tple_select"> <select id="tple_fillin_num" class="tple_fillin_num"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <nobr class="tple_fillin_num_">小题数</nobr> </div> </div> </div> <div class="tple_ans"> <nobr class="tple_ans_">答案</nobr> <div id="tple_empty" style="height: 45px;"></div> <div class="tple_answer"> <form id="tple_single" class="tple_single tple_tple"> <input id="tple_single_A" type="radio" name="single" value="A"><label for="tple_single_A">A</label> <input id="tple_single_B" type="radio" name="single" value="B"><label for="tple_single_B">B</label> <input id="tple_single_C" type="radio" name="single" value="C"><label for="tple_single_C">C</label> <input id="tple_single_D" type="radio" name="single" value="D"><label for="tple_single_D">D</label> </form> <form id="tple_many" class="tple_many tple_tple"> <input id="tple_many_A" type="checkbox" name="many" value="A" ><label for="tple_many_A">A</label> <input id="tple_many_B" type="checkbox" name="many" value="B"><label for="tple_many_B">B</label> <input id="tple_many_C" type="checkbox" name="many" value="C"><label for="tple_many_C">C</label> <input id="tple_many_D" type="checkbox" name="many" value="D"><label for="tple_many_D">D</label> </form> <form id="tple_judge" class="tple_judge tple_tple"> <input id="tple_judge_√" type="radio" name="judge" checked="checked" value="对"><label for="tple_judge_√">√</label> <input id="tple_judge_×" type="radio" name="judge" value="错"><label for="tple_judge_×">×</label> </form> <div id="tple_fillin" class="tple_fillin tple_tple"></div> <div id="tple_text" class="tple_text tple_tple tple_textarea"> <script id="tple_text_text" type="text/plain" style="700px;height:150px;"></script> </div> </div> </div> <div class="tple_button"> <button id="tple_ctuadd" class="tple_ctuadd tple_sub">继续添加</button> <button id="tple_sas" class="tple_sas tple_sub">保存预览</button> </div> </div> <div class="side-bar"> <a href="javascript:void(0);" onclick="showQuesTempFn()" class="icon-qq" title="题库模板"></a> <a href="javascript:void(0);" onclick="showMycollectFn()" class="icon-chat" title="我的收藏"></a> <a href="javascript:void(0);" onclick="hideFn()" class="icon-blog" title="关闭模板"></a> <a href="#container" class="icon-mail" title="回到顶部" ></a> </div> <div class="zz_bg" > <div class="zz_show"> </div> </div> <script type="text/javascript"> var userData = new Object(); userData.user_id = "${param.user_id}"; userData.homework_id = "${param.homework_id}"; userData.section_id = "${param.section_id}"; userData.textbook_id = "${param.textbook_id}"; userData.homework_name = "${param.homework_name}"; userData.worktype = "${param.worktype}"; userData.que_no = "${param.que_no}"; $.extend({ 'tple_choose' : function(id, type) { $("#" + type + "").show(); $("#" + type + "").siblings().hide(); } }); var ue,ue1,bool=true; // 保存试题参数 var queNo = userData.que_no; var squeParam = { homework_id : userData.homework_id, question_no : queNo }; var count1 = 1, count2, fillinNum = 1; $(document) .ready( function() { ue = UE.getEditor('tple_stem_text', { serverUrl: "${ctx}/work/hw/getImgServer.ac", toolbars: [ [ 'sxgs',//手写公式 'undo', //撤销 'redo', //重做 'formatmatch', //格式刷 'removeformat', //清除格式 'simpleupload', //单图上传 // 'insertimage', //多图上传 'searchreplace', //查询替换 'justifyleft', //居左对齐 'justifyright', //居右对齐 'justifycenter', //居中对齐 'justifyjustify', //两端对齐 'insertorderedlist', //有序列表 'insertunorderedlist', //无序列表 'fullscreen' //全屏 ] ], autoHeightEnabled: false }); ue1 = UE.getEditor('tple_text_text', { serverUrl: "${ctx}/work/hw/getImgServer.ac", toolbars: [ [ 'sxgs1',//手写公式 'undo', //撤销 'redo', //重做 'formatmatch', //格式刷 'removeformat', //清除格式 'searchreplace', //查询替换 'justifyleft', //居左对齐 'justifyright', //居右对齐 'justifycenter', //居中对齐 'justifyjustify', //两端对齐 'insertorderedlist', //有序列表 'insertunorderedlist', //无序列表 'fullscreen' //全屏 ] ], autoHeightEnabled: true, autoFloatEnabled: true }); //手写公式 baidu.editor.commands['sxgs'] = { execCommand: function() { var bool=jdllqFn(); if(bool){ var win = mini.open({ url : "${ctx}/scripts/bower_components/myscript-math-web/demo/aa.html", title : "手写公式", width : 800, height : 500, showMaxButton : true, ondestroy : function(action) { if(action&&action!="close"){ var latexImg="<img src='http://latex.codecogs.com/gif.latex?"+action.LATEX+"'/>"; var str=ue.getContent()+latexImg; ue.setContent(str,false); } } }); } return true; }, queryCommandState: function() { } }; //手写公式 baidu.editor.commands['sxgs1'] = { execCommand: function() { var bool=jdllqFn(); if(bool){ var win = mini.open({ url : "${ctx}/scripts/bower_components/myscript-math-web/demo/aa.html", title : "手写公式", width : 800, height : 500, showMaxButton : true, ondestroy : function(action) { if(action&&action!="close"){ var latexImg="<img src='http://latex.codecogs.com/gif.latex?"+action.LATEX+"'/>"; var str=ue1.getContent()+latexImg; ue1.setContent(str,false); } } }); } return true; }, queryCommandState: function() { } }; $(".tple_tple").hide(); $(".tple_select").hide(); $(".tple_type_bt").on('mousedown',function() { var tple_type = $(this).val(); $(this).removeClass("tple_type_bt_nochecked") .addClass("tple_type_bt_checked"); $(this).siblings().removeClass("tple_type_bt_checked") .addClass("tple_type_bt_nochecked"); $.tple_choose(this, tple_type); switch (tple_type) { case "tple_single": squeParam.question_type = 1; $(".tple_select").hide(); $("#tple_empty").hide(); break; case "tple_many": squeParam.question_type = 2; $(".tple_select").hide(); $("#tple_empty").hide(); break; case "tple_judge": squeParam.question_type = 3; $(".tple_select").hide(); $("#tple_empty").hide(); break; case "tple_fillin": squeParam.question_type = 4; $(".tple_select").show(); $("#tple_empty").hide(); break; case "tple_text": squeParam.question_type = 5; $(".tple_select").hide(); $("#tple_empty").hide(); break; default: break; } }); //填空题动态生成答案空 //初始生成个空 $("#tple_fillin").append( "<div class='tple_fillin_item'><input type='text' class='tple_fillin_number' readonly='readonly' value='(" + fillinNum + ")'><input type='text' class='tple_fillin_empty'><div class='tple_fillin_bt'><button onclick='onAddClick(this)' class='tple_add'></button><button onclick='onMinusClick(this)' class='tple_minus'></button></div></div>"); $("#tple_fillin_num").on('change',function() { count2 = $(this).val(); if (count2 > count1) { for (var i = 0; i < (count2 - count1); i++) { fillinNum++; $("#tple_fillin").append( "<div class='tple_fillin_item'><input type='text' class='tple_fillin_number' readonly='readonly' value='(" + fillinNum + ")'><input type='text' class='tple_fillin_empty'><div class='tple_fillin_bt'><button onclick='onAddClick(this)' class='tple_add'></button><button onclick='onMinusClick(this)' class='tple_minus'></button></div></div>"); } } else if (count2 < count1) { for (var j = 0; j < (count1 - count2); j++) { $(".tple_fillin_item").last().remove(); fillinNum--; } } count1 = count2; }); /* * 保存当前试题,继续添加试题 */ var squeUrl = "work/addquestions"; $("#tple_ctuadd").on('click',function() { var str=ue.getContent(); str=str.replace(/\cfs/pictures//g, ""); str=replaceSXGS(str); squeParam.stem_text =str; switch (squeParam.question_type) { case 1: squeParam.reference_answers_text = $("#tple_single input[name='single']:checked").val(); break; case 2: var manyCheck = ""; $("#tple_many input[name=many]:checked").each(function() { manyCheck += $(this).val(); }); squeParam.reference_answers_text = manyCheck; break; case 3: squeParam.reference_answers_text = $("#tple_judge input[name='judge']:checked").val(); break; case 4: var fillinStr = ""; $(".tple_fillin_empty").each(function() { fillinStr += $(this).val() + "#"; }); squeParam.reference_answers_text = fillinStr.substring(0,fillinStr.lastIndexOf("#")); break; case 5: var s=ue1.getContentTxt(); if(s=="略"||s=="略."||s=="略.."||s=="略..."||s=="略...."||s=="略....."){ squeParam.reference_answers_text="略"; }else{ var str1=ue1.getContent(); str1=str1.replace(/\cfs/pictures//g, ""); squeParam.reference_answers_text =str1; } break; } if ((squeParam.stem_text || squeParam.stem_picture) && (squeParam.reference_answers_text || squeParam.reference_answers_pciture)) { $.ajax({ url : path + squeUrl, type : "POST", contentType : "application/json; charset=utf-8", dataType : "json", data : squeParam, success : function(data) { if(data[0].flag){ queNo++; $("#nwself_container").empty().load('/cfs/work/hw/tplehw.ac' ,{ user_id : userData.user_id, homework_id : userData.homework_id, section_id : userData.section_id, textbook_id : userData.textbook_id, homework_name : userData.homework_name, worktype : "${worktype}", que_no : queNo }); } }, error : function() { alert("请求接口失败"); } }); squeParam.question_no++; }else{ mini.alert("请先完善题干及参考答案"); } }); /* * 保存预览所有试题 */ $("#tple_sas").on('click',function(event) { event.preventDefault(); var str=ue.getContent(); str=str.replace(/\cfs/pictures//g, ""); str=replaceSXGS(str); squeParam.stem_text =str; switch (squeParam.question_type) { case 1: squeParam.reference_answers_text = $( "#tple_single input[name='single']:checked") .val(); break; case 2: var manyCheck = ""; $("#tple_many input[name=many]:checked").each(function() { manyCheck += $(this).val(); }); squeParam.reference_answers_text = manyCheck; break; case 3: squeParam.reference_answers_text = $( "#tple_judge input[name='judge']:checked") .val(); break; case 4: var fillinStr = ""; $(".tple_fillin_empty").each(function() { fillinStr += $(this).val() + "#"; }); squeParam.reference_answers_text = fillinStr.substring(0,fillinStr.lastIndexOf("#")); break; case 5: var s=ue1.getContentTxt(); if(s=="略"||s=="略."||s=="略.."||s=="略..."||s=="略...."||s=="略....."){ squeParam.reference_answers_text="略"; }else{ var str1=ue1.getContent(); str1=str1.replace(/\cfs/pictures//g, ""); squeParam.reference_answers_text =str1; break; } } if ((squeParam.stem_text || squeParam.stem_picture) && (squeParam.reference_answers_text || squeParam.reference_answers_pciture)) { $.ajax({ url : path + squeUrl, type : "POST", contentType : "application/json; charset=utf-8", dataType : "json", data : squeParam, success : function(data) { if(data[0].flag){ $("#nwself_container").empty().load('/cfs/work/hw/previewhw.ac' ,{ user_id : userData.user_id, homework_id : userData.homework_id, section_id : userData.section_id, textbook_id : userData.textbook_id, homework_name : userData.homework_name, worktype : "${worktype}" }); } }, error : function() { alert("请求接口失败"); } }); }else{ mini.alert("请先完善题干及参考答案"); } }); //返回上一页 $("#tple_back").on('mousedown',function(){ location.reload(); }); // 初始化Mathjax MathJax.Hub.Queue([ "Typeset", MathJax.Hub ]); }); function replaceSXGS(str){ if(str){ var v="http://latex.codecogs.com/gif.latex?"; if(str.indexOf(v)!=-1){ var s=str.substring(str.indexOf(v)+v.length,str.length); s=s.substring(0,s.indexOf('"')); var mystr='<img src="http://latex.codecogs.com/gif.latex?';//"<img src='http://latex.codecogs.com/gif.latex?"+s+"'/>"; var re = new RegExp(mystr); str=str.replace(re, "").replace(s,"news").replace(/news"/>/,"\("+s+"\)" ).replace(/?/,""); str=replaceSXGS(str); } } return str; } function onAddClick(a) { var placeLength = $(a).parent().parent().children(".tple_fillin_empty").length; if(placeLength > 10){ mini.alert("每个小题最多有10个空"); return; } $(a).parent().before("<input type='text' class='tple_fillin_empty'>"); } function onMinusClick(a) { var placeLength = $(a).parent().parent().children(".tple_fillin_empty").length; if(placeLength <= 1){ mini.alert("每个小题至少有1个空"); return; } $(a).parent().prev().remove(".tple_fillin_empty"); } //点击试题模板 function showQuesTempFn(){ $.ajax({ url : path + "work/classhour", type : "POST", contentType : "application/json; charset=utf-8", dataType : "json", async:false, data : {textbook_id:userData.textbook_id,section_id:userData.section_id,user_id:userData.user_id}, success : function(data) { if(data[0].flag){ var str=""; $.each(data[0].questions,function(i,e){ var id=e.id; var question_no=e.question_no; var question_type=e.question_type=="1"?"单选题":"写作题"; var stem_text=e.stem_text; var reference_answers_text=e.reference_answers_text; str+="<div class='ques_bg' onmousemove='onmousemoveFn(this)' onmouseout='onmouseoutFn(this)' ondblclick='ondbclickFn(this)' >" +"<font>题型:</font><span class='ques_tx'>"+question_type+"</span>" +"<div class='ques_tg' myTitle='"+stem_text+"'>" +stem_text +"</div>" +"<font class='ques_ckda'>参考答案:</font><span class='ques_font' myTitle='"+reference_answers_text+"'>"+reference_answers_text+"</span>" +"</div>"; }); if(str!=""){ $(".zz_show").html(str); }else{ $(".zz_show").html("<img class='haveno_data' src='${ctx}/image/images/goupsd.png'>"); } MathJax.Hub.Queue([ "Typeset", MathJax.Hub ]); showFn(); } }, error : function() { alert("请求接口失败"); } }); } //点击我的收藏试题模板 function showMycollectFn(){ $.ajax({ url : path + "collect/view", type : "POST", contentType : "application/json; charset=utf-8", dataType : "json", async:false, data : {user_id:userData.user_id}, success : function(data) { if(data[0].flag){ var str=""; $.each(data[0].questions,function(i,e){ var question_id=e.question_id; var stem_text=e.stem_text.replace(/</g,"<").replace(/>/g,">"); var question_type="其他题"; if(e.question_type=="1"){ question_type="单选题" }else if(e.question_type=="2"){ question_type="多选题" }else if(e.question_type=="3"){ question_type="判断题" }else if(e.question_type=="4"){ question_type="填空题" }else if(e.question_type=="5"){ question_type="写作题" } var oldReference_text=e.reference_answers_text; var reference_answers_text=replaceText(e.reference_answers_text); var stem_picture=getImgStr(e.stem_picture); var reference_answers_pciture=getImgStr(e.reference_answers_pciture); if(!stem_text||stem_text==null||stem_text==""){ stem_text=stem_picture; }else{ if(stem_picture!=null&&stem_picture!=""){ stem_text=stem_text+"<br/>"+stem_picture; } } if(!reference_answers_text||reference_answers_text==null||reference_answers_text==""){ reference_answers_text=reference_answers_pciture; }else{ if(reference_answers_pciture!=null&&reference_answers_pciture!=""){ reference_answers_text=reference_answers_text+"<br/>"+reference_answers_pciture; } } str+="<div class='ques_bg' onmousemove='onmousemoveFn(this)' onmouseout='onmouseoutFn(this)' ondblclick='ondbclickFn(this)' >" +"<font>题型:</font><span class='ques_tx'>"+question_type+"</span>" +"<div class='ques_tg' myTitle='"+stem_text+"'>" +stem_text +"</div>" +"<font class='ques_ckda'>参考答案:</font><span class='ques_font' oldvalue='"+oldReference_text+"' myTitle='"+reference_answers_text+"' >"+reference_answers_text+"</span>" +"</div>"; }); if(str!=""){ $(".zz_show").html(str); }else{ $(".zz_show").html("<img class='haveno_data' src='${ctx}/image/images/goupsd.png'>"); } MathJax.Hub.Queue([ "Typeset", MathJax.Hub ]); showFn(); } }, error : function() { alert("请求接口失败"); } }); } function getImgStr(s){ var mystr=""; if(s){ var str=s.split(","); for (var y = 0; y < str.length; y++) { mystr+="<br/><img src='"+str[y]+"' />"; } } return mystr; } //鼠标移入事件 function onmousemoveFn(e){ $(e).css("background-color","#F1F1F1"); } //鼠标移入事件 function onmouseoutFn(e){ $(e).css("background-color","white"); } //鼠标双击事件 function ondbclickFn(e){ var tg=$(e).find(".ques_tg").attr("myTitle"); tg=tg.replace(/ /g," "); var tx=$(e).find(".ques_tx").text(); var ckda=$(e).find(".ques_font").attr("myTitle"); var temp=$("button[value='tple_single']"); var tple_type ="tple_single"; if(tx=="单选题"){ temp=$("button[value='tple_single']"); tple_type ="tple_single"; $("input:radio[name='single'][value='"+ckda+"']").attr("checked",true); }else if(tx=="多选题"){ temp=$("button[value='tple_many']"); tple_type ="tple_many"; var strs=ckda.split(""); for (var i = 0; i < strs.length; i++) { $("input:checkbox[name='many'][value='"+strs[i]+"']").attr("checked",true); } }else if(tx=="判断题"){ temp=$("button[value='tple_judge']"); tple_type ="tple_judge"; $("input:radio[name='judge'][value='"+ckda+"']").attr("checked",true); }else if(tx=="填空题"){ temp=$("button[value='tple_fillin']"); tple_type ="tple_fillin"; var tkt=$(".tple_fillin_empty").eq(0); $(".tple_fillin_empty").not(tkt).remove(); var ckdas=ckda.split(" ; "); if(ckdas.length==1){ tkt.val(ckdas[0]); }else if(ckdas.length>1){ var len=ckdas.length%10==0?parseInt(ckdas.length/10):parseInt(ckdas.length/10)+1; if(len>1){ $("#tple_fillin").html(""); var num=1; for (var i = 1; i <= len; i++) { var inputstr=""; for (var j = num; j <ckdas.length; j++) { inputstr+="<input type='text' class='tple_fillin_empty' value='"+ckdas[j]+"'>"; if(j==i*10){ num=j+1; break; } } $("#tple_fillin").append( "<div class='tple_fillin_item'><input type='text' class='tple_fillin_number' readonly='readonly' value='(" + i + ")'>"+inputstr+"<div class='tple_fillin_bt'><button onclick='onAddClick(this)' class='tple_add'></button><button onclick='onMinusClick(this)' class='tple_minus'></button></div></div>"); $("#tple_fillin_num").val(len); count1=len; fillinNum = len; } }else{ var inputstr=""; tkt.val(ckdas[0]); for (var i = 1; i < ckdas.length; i++) { inputstr+="<input type='text' class='tple_fillin_empty' value='"+ckdas[i]+"'>"; } tkt.after(inputstr); } } //var oldvalue=$(e).find(".ques_font").attr("oldvalue"); //alert(oldvalue); }else if(tx=="写作题"){ temp=$("button[value='tple_text']"); tple_type ="tple_text"; ue1.setContent(ckda,false); } ue.setContent(tg,false); hideFn(); temp.removeClass("tple_type_bt_nochecked") .addClass("tple_type_bt_checked"); temp.siblings().removeClass("tple_type_bt_checked") .addClass("tple_type_bt_nochecked"); $.tple_choose(temp, tple_type); switch (tple_type) { case "tple_single": squeParam.question_type = 1; $(".tple_select").hide(); $("#tple_empty").hide(); break; case "tple_many": squeParam.question_type = 2; $(".tple_select").hide(); $("#tple_empty").hide(); break; case "tple_judge": squeParam.question_type = 3; $(".tple_select").hide(); $("#tple_empty").hide(); break; case "tple_fillin": squeParam.question_type = 4; $(".tple_select").show(); $("#tple_empty").hide(); break; case "tple_text": squeParam.question_type = 5; $(".tple_select").hide(); $("#tple_empty").hide(); break; default: break; } } var is_show=false; //作业模板列表 function showFn() { if(is_show){ hideFn; } $(".zz_bg").show(); $(".zz_show").show().stop().animate({left: "60px"},1000); is_show=true; } //关闭作业模板列表 function hideFn() { if(is_show){ $(".zz_show").css("left","100%"); $(".zz_bg").hide(); is_show=false; }else{ mini.showTips({ content: "<b>操作失败</b> <br/>试题模板和我的收藏列表还没有展开!", state: "danger", x: "center", y: "center", timeout: 3000 }); } } function myBrowser(){ var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 var isOpera = userAgent.indexOf("Opera") > -1; if (isOpera) { return "Opera" }; //判断是否Opera浏览器 if (userAgent.indexOf("Firefox") > -1) { return "FF"; } //判断是否Firefox浏览器 if (userAgent.indexOf("Chrome") > -1){ return "Chrome"; } if (userAgent.indexOf("Safari") > -1) { return "Safari"; } //判断是否Safari浏览器 if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("IE") > -1 && !isOpera) { return "IE"; }; //判断是否IE浏览器 } function jdllqFn(){ var bool=false; //以下是调用上面的函数 var mb = myBrowser(); if ("IE" == mb) { showTips('IE'); } if ("FF" == mb) { showTips('Firefox'); } if ("Chrome" == mb) { // showTips('Chrome'); bool=true; } if ("Opera" == mb) { showTips('Opera'); } if ("Safari" == mb) { showTips('Safari'); } return bool; } function showTips(s){ mini.showTips({ content: "<div align='left'><b>当前浏览器为"+s+"浏览器,目前该功能暂不支持本浏览器</b>;<br/>为了您更好的体验,强烈建议您使用Chrome(谷歌)浏览器来访问我们的程序;<br/><a href='https://www.baidu.com/link?url=y_mhmYxO2nC4io-7niCrOLQmHD9R09JvAzqBTdDJYRiZ2X9zh3vPI_xSeAg30UnRCoafIhXMb3l3zu8TtMAfN7eHjGF012MujHi0TyhXH97&wd=&eqid=d1a8af080002b2220000000258004958' target='_blank'>点击此处下载浏览器</a>,感谢配合!</div>", state: "danger", x: "center", y: "center", timeout: 10000 }); } </script> </body> </html>
关键代码:
var latexImg="<img src='http://latex.codecogs.com/gif.latex?"+action.LATEX+"'/>"; var str=ue1.getContent()+latexImg; ue1.setContent(str,false);//ue1为Ueditor富文本编辑器对象
七、将富文本中的图片公式转化为Latex格式的字符串
function replaceSXGS(str){ if(str){ var v="http://latex.codecogs.com/gif.latex?"; if(str.indexOf(v)!=-1){ var s=str.substring(str.indexOf(v)+v.length,str.length); s=s.substring(0,s.indexOf('"')); var mystr='<img src="http://latex.codecogs.com/gif.latex?';//"<img src='http://latex.codecogs.com/gif.latex?"+s+"'/>"; var re = new RegExp(mystr); str=str.replace(re, "").replace(s,"news").replace(/news"/>/,"\("+s+"\)" ).replace(/?/,""); str=replaceSXGS(str); } } return str; }
上述是在保存时将富文本里的值获取到然后通过这个方法转化为干净的Latex公式。
八、正常的DIV里是如何显示的呢?这里使用的是mathjax来操作的,只需要2步:
1、下载插件:
2、集成mathjax,只需要在对应的jsp里引入下面的文件
<script type="text/javascript" src="${ctx}/scripts/mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full"></script>
注意:${ctx}/表示我项目的上下文,这里因项目而异,不用过于纠结于此。
3、引入文件后,只需要在窗体加载完毕的事件里或script最后一行里写上这句话即可。
<script type="text/javascript">
MathJax.Hub.Queue([ "Typeset", MathJax.Hub ]);//将这句话放到窗体加载完毕的事件里即可,只要确定页面的数据已经渲染完毕再执行此语句就行。 </script>
OK,经过一系列的集成你的项目是否已经可以正常使用了呢,让我们一起来看看最后的效果图吧!
好了,演示完毕,小伙伴们,快来集成试试吧。