通过引入markdown.js来实现文本的预览,这篇所写的是实现同步滚动
scroll.js
var editor=document.getElementById('editor'); //输入框
var preview=document.getElementById('preview'); //markdown
var hintbar=document.getElementById('hintbar'); //进度条
function Editor(editor,preview){ //将输入框内容复制到markdown上
this.update=function(){
preview.innerHTML=markdown.toHTML(input.value);
};
input.editor=this;
this.update();
}
new Editor(editor,preview);
function update(src,dest,hint){ //update将三部分UI耦合在一起
var scrollRange=src.scrollHeight-src.clientHeight,
p=src.scrollTop/scrollRange;
dest.scrollTop=p*(dest.scrollHeight-dest.clientHeight);
hint.innerHTML=Math.round(100*p)+'%';
}
update(editor,preview,hintbar);
function monopoly(fn,duration){ //获得允许调用该函数的权限,排斥其他函数的调用
duration=duration || 100;
var ret=function(){
if(!monopoly.permit){
monopoly.permit=fn;
}
if(monopoly.permit === fn){
clearTimeout(monopoly.permitTimer);
monopoly.permitTimer=setTimeout(function(){
delete monopoly.permit;
},duration);
return fn.apply(this,arguments);
}
}
return ret;
}
editor.addEventListener('scroll',monopoly(function(evt){ //editor滑动
update(editor,preview,hintbar);
}));
preview.addEventListener('scroll',monopoly(function(evt){ //preview滑动
update(preview,editor,hintbar);
}));
scroll.js中为输入部分和预览部分都定义scroll事件,但是双向的滚动会影响彼此,所以重点在于定义monopoly来排斥其他函数的调用。
<body>
<textarea id="editor" rows="20" cols="30" oninput="this.editor.update()"></textarea>
<div id="preview"></div>
<p id="hintbar"></p>
<script type="text/javascript" src="markdown.js"></script>
<script type="text/javascript" src="scroll.js"></script>
</body>