需求:模拟markdown文件

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
html,body{
	margin: 0;
	padding: 0;
	width: 100%;
	height: 100%;
	overflow: hidden;
}
textarea{
	width: 48%;
	height: 100%;
	float: left;
}
#box{
	width: 50%;
	height: 100%;
	overflow: scroll;
	float: left;
}
.node{
	background: rgba(0,0,0,.05);
}
.nodeB{
	background: #2d2d2d;
}
</style>
</head>
<body>
<textarea id='textNode'></textarea>
<div id='box'></div>
<script type="text/javascript">
var textNode = document.getElementById('textNode');
var tm;
textNode.onkeyup = function() {
	clearTimeout(tm);
	tm = setTimeout(fn, 500);
}
function fn(e) {
	var codeFlag = false;// 用于判断代码双标签
	var textValue = textNode.value;
	var arr = textValue.split(/\r|\n/g).filter(function (s) {
		return s && s.trim(); // 注:IE9(不包含IE9)以下的版本没有trim()方法
	});
	arr = arr.map(function(item) {
		if(!codeFlag) {
			if(/^```/.test(item)) {
				codeFlag = true;
				if(/`$/.test(item)){
					return "<div class='node'>";
				}
				return "<div class='nodeB'>";
			}
			if(/^#/.test(item)) {
				var tit = item.substring(0,item.indexOf(' ')),
					len = tit.length,
					str = item.substring(item.indexOf(' ') + 1);
				if (len <= 6) {
					item = item.replace(str, `${str}</h${len}>`).replace(tit, `<h${len}>`);

				}
			}
			if(/\!\[tmall\]\(.+\)/.test(item)){
				str = item.substring(item.indexOf('![tmall](') + 1, item.length -1);
				item.match(/\!\[.+\]\(.+\)/).forEach(function(i) {
					var alt = /\!\[(.+)\]/.exec(i)[1];
					var src = /\((.+)\)/.exec(i)[1];
					item = item.replace(i, `<img src=${src} alt=${alt}/>`);
				})
			}
			if(/\[.+]\(.+\)/.test(item)){
				item.match(/\[.+]\(.+\)/).forEach(function(i) {
					var href = /\((.+)\)/.exec(i)[1];
					var text = /\[(.+)\]/.exec(i)[1];
					item = item.replace(i, `<a href=${href}>${text}</a>`);
				})
			}
		}
		if(/^```/.test(item)) {
			codeFlag = false;
			return "</div>";
		}
		return item;
	});
	console.log(arr);
	var box1 = document.getElementById('box');
	box1.innerHTML = arr;
}
</script>
</body>
</html>

未完待续

01-15 14:47