模拟在 md2all 的编辑器中 逐字输入 ,并触发预览区 markdown 渲染。

思路:

每隔100毫秒,取出文本下一个字符,插入到 textarea 光标位置,模拟键盘按键事件,触发预览区渲染。

  • textarea 中 回车 与 \需要转义;
  • charAt(index) 结合索引依次取字符串中的单个字符;
  • setInterval 定时调用插入函数,遍历字符串后 clearInterval 结束定时任务。

代码如下:


//模拟按键
var textbox = document.getElementById("editor"),event; 
    if (document.implementation.hasFeature("KeyboardEvents", "3.0")){ 
      event = document.createEvent("KeyboardEvent"); 
      event.initKeyboardEvent("keydown", true, true, document.defaultView, "a",0, "enter", 0); 
    } 
function act_key() {
 	// body...
	textbox.dispatchEvent(event);
 } 


var myTxt = "> Markdown ,极客,即刻开始。\n\n### 小试牛刀\n![go](https://nickhoo.com/nick.png)\n\n$$H(D_2) = -(\\frac{2}{4}\\ log_2 \\frac{2}{4} + \\frac{2}{4}\\ log_2 \\frac{2}{4}) = 1$$\n\n- [x] 任务1;\n- [ ] 任务2;\n\n```JS\nfunction add(a,b)\n{\n  return a+b;\n}\n``` \n"

;

//插入到光标   
function insertAtCursor(myField, myValue) {
    if (document.selection) {
        //IE support
        myField.focus();
        sel = document.selection.createRange();
        sel.textbox = myValue;
        sel.select();
    } else if (myField.selectionStart || myField.selectionStart == '0') {
        //MOZILLA/NETSCAPE support
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        var beforeValue = myField.value.substring(0, startPos);
        var afterValue = myField.value.substring(endPos, myField.value.length);

        myField.value = beforeValue + myValue + afterValue;

        myField.selectionStart = startPos + myValue.length;
        myField.selectionEnd = startPos + myValue.length;
        myField.focus();
    } else {
        myField.value += myValue;
        myField.focus();
    }
}
//遍历字符串
var ind = 0;
function gogogo()
{
	
	if(ind <= myTxt.length)
	{
		
	 	
	 		var char_insert = myTxt.charAt(ind);
		 	insertAtCursor(textbox,char_insert);
		 	//模拟按键
		 	act_key();

	 	ind ++;

	}
	else
	 	{
	 		t=clearInterval(t);
	 	}
}
//定时调用
var t = setInterval("gogogo()",100);