在工作中,经常使用CodeMirror高亮插件时会遇到高度需要同步自适应外层容器的问题(宽度是很好设定的,由容器决定),现写了以下代码进行实现,特此记录下来,以备后用:
//改变父div时同步改变CodeMirror的高度
function setHeightByDiv(codeEditor,height){
var scroller = codeEditor.getScrollerElement();
var gutter = codeEditor.getGutterElement();
$(scroller).height(height);
$(gutter).height(height);
}
然后调用:
//初始化文本区显示内容的高亮插件对象
var scriptFiledCodeEditor = CodeMirror.fromTextArea($("#scriptFiled")[0], {
mode: "javascript",
styleActiveLine: true,
lineNumbers:true,
lineWrapping:true
});
$(function(){
//渲染完成后查找tab的内容高度
var tabBodyHeight = $('#templateLook').layout('panel','center').height();
//设置脚本展示tab的上面编辑器高度
setHeightByDiv(scriptFiledCodeEditor,tabBodyHeight);
});