实现简易版markdown同步滚动

通过引入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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值