手把手集成web端手寫公式功能


何為手寫公式,很簡單,就是在網頁上可以寫出數學公式,並能夠生成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;width: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()" />
&nbsp;&nbsp;
<img src="close.png" onmouseover="mouseOver1(this)" onmouseout="mouseOut1(this)" title="關閉" class="myimg" onclick="closeFn()" />

</div>
</body>
</html>
項目使用的手寫公式html

就在四點中文件夾下bower_components\myscript-math-web\demo\aa.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 {
width: 800px;
height: 170px;
}

.tple_que {
width:
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 {
width: 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 {
width: 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 {
width: 23px;
height: 20px;
margin: 15px
0 0 40px;
}

.container label {
position: relative;
left: 6px;
bottom: 3px;
font
-size: 20px;
font
-family: 黑體;
}

.tple_fillin_item {
width:
90%;
margin
-left: 7%;
height: 50px;
float: left;
}

.tple_fillin_empty {
width: 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 {
width: 800px;
}

.tple_fillin_number {
width: 50px;
text
-align: center;
border: none;
float: left;
}

tple_fillin_bt {
margin: 10px
0 0 10px;
float: left;
}

.tple_add {
width: 22px;
height: 22px;
margin
-left: 5px;
border: none;
outline:
0;
background: url(
/cfs/image/images/homeworktemplate_fillin_add.png)
no
-repeat;
}

.tple_minus {
width: 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 {
width: 500px;
height: 45px;
margin
-top: 120px;
}

.tple_sub {
width: 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 {width: 66px;position: fixed;bottom: 20px;right: 25px;font-size: 0;line-height: 0;z-index: 1003;}
.side
-bar a {width: 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 {width: 9px;height: 16px;display: inline-block;position: absolute;right: -9px;top: 80px;background-position:-88px -350px;}
.chat
-tips img {width: 138px;height: 138px;}

.zz_bg{display: none; position: absolute; top:
0%; left: 0%; width: 100%; height: 100%;z-index: 1001;overflow:hidden; }
.zz_show{display: none; position: absolute; top:
12%; left: 100%; width: 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="width: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="width: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(/&lt/g,"<").replace(/&gt/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(/&nbsp;&nbsp;/g,"&nbsp;");
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,經過一系列的集成你的項目是否已經可以正常使用了呢,讓我們一起來看看最后的效果圖吧!

好了,演示完畢,小伙伴們,快來集成試試吧。

  


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com