2013-07-15 2 views
3

기본 CodeMirror HTML 편집기 - http://jsfiddle.net/D9MvH/1/ -을 FileReader API를 CodeMirror에 http://liveweave.com/zSqCfA을 FileReader와 CodeMirror 파일로드 합병증

파일로드 - http://liveweave.com/VvsXN9

는 여기에 내가 할 노력하고있어 매우 간단한 예입니다. (이러한 온라인 편집기에서는 저장 기능이 작동하지 않지만 가져 오기 파일 기능은이 간단한 편집기에서 작동합니다.) - http://liveweave.com/MrUBfZ

내 입력 파일 양식을 클릭하여 파일을 탐색 할 때 문제가 발생합니다. 열 수있는 HTML 문서를 선택하고 CodeMirror에서 /로 열리지 않습니다. 나는 내 지식을 다 해봤지만 제대로 작동하지 않습니다. 아무도 이것으로 도울 수 있습니까?

HTML :

<input type="file" onchange="loadfile(this)"> 

자바 스크립트 :

var delay; 

// Initialize CodeMirror editor 
var editor = CodeMirror.fromTextArea(document.getElementById('code'), { 
    mode: 'text/html', 
    tabMode: 'indent', 
    lineNumbers: true, 
    lineWrapping: true, 
    autoCloseTags: true 
}); 

// Live preview 
editor.on("change", function() { 
    clearTimeout(delay); 
    delay = setTimeout(updatePreview, 300); 
}); 

function updatePreview() { 
    var previewFrame = document.getElementById('preview'); 
    var preview = previewFrame.contentDocument || previewFrame.contentWindow.document; 
    preview.open(); 
    preview.write(editor.getValue()); 
    preview.close(); 
} 
setTimeout(updatePreview, 300); 

function saveTextAsFile() { 
    var textToWrite = document.getElementById("code").value; 
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'}); 
    var fileNameToSaveAs = "myfile.html"; 

    var downloadLink = document.createElement("a"); 
    downloadLink.download = fileNameToSaveAs; 
    downloadLink.innerHTML = "Download File"; 
    if (window.webkitURL != null) 
    { 
     // Chrome allows the link to be clicked 
     // without actually adding it to the DOM. 
     downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); 
    } 
    else 
    { 
     // Firefox requires the link to be added to the DOM 
     // before it can be clicked. 
     downloadLink.href = window.URL.createObjectURL(textFileAsBlob); 
     downloadLink.onclick = destroyClickedElement; 
     downloadLink.style.display = "none"; 
     document.body.appendChild(downloadLink); 
    } 

    downloadLink.click();} 

function destroyClickedElement(event) { 
    document.body.removeChild(event.target);} 

function loadfile(input){ 
    var reader = new FileReader() 
    reader.onload = function(e) { 
     editor.setValue = e.target.result;} 
    reader.readAsText(input.files[0]);} 

    var input = document.getElementById("select"); 

    function selectTheme() { 
     var theme = input.options[input.selectedIndex].innerHTML; 
     editor.setOption("theme", theme); 
    } 

    var choice = document.location.search && 
       decodeURIComponent(document.location.search.slice(1)); 
    if (choice) { 
     input.value = choice; 
     editor.setOption("theme", choice); 
    } 

전체 코드

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>CodeMirror: HTML5 preview</title> 
<script src='http://codemirror.net/lib/codemirror.js'></script> 
<script src='http://codemirror.net/mode/xml/xml.js'></script> 
<script src='http://codemirror.net/mode/javascript/javascript.js'></script> 
<script src='http://codemirror.net/mode/css/css.js'></script> 
<script src='http://codemirror.net/mode/htmlmixed/htmlmixed.js'></script> 
<link rel='stylesheet' href='http://codemirror.net/lib/codemirror.css'> 
<link rel='stylesheet' href='http://codemirror.net/doc/docs.css'> 
<style type='text/css'> 
.CodeMirror { 
    float: left; 
    width: 50%; 
    border: 1px solid black;} 

iframe { 
    width: 49%; 
    float: left; 
    height: 300px; 
    border: 1px solid black; 
    border-left: 0px;} 
</style> 
</head> 
<body> 
    <textarea id="code" name="code"><!doctype html> 
<html> 
<head> 
<meta charset=utf-8> 
<title>HTML5 canvas demo</title> 
<style>p {font-family: monospace;}</style> 
</head> 
<body> 
    <p>Canvas pane goes here:</p> 
    <canvas id=pane width=300 height=200></canvas> 

    <script> 
     var canvas = document.getElementById('pane'); 
     var context = canvas.getContext('2d'); 

     context.fillStyle = 'rgb(250,0,0)'; 
     context.fillRect(10, 10, 55, 50); 

     context.fillStyle = 'rgba(0, 0, 250, 0.5)'; 
     context.fillRect(30, 30, 55, 50); 
    </script> 
</body> 
</html></textarea> 

    <iframe id="preview"></iframe> 

    <input type="file" onchange="loadfile(this)"> 
    <a href="#my-header" onclick='saveTextAsFile()'>Save/Download</a> 

<script> 
var delay; 

// Initialize CodeMirror editor 
var editor = CodeMirror.fromTextArea(document.getElementById('code'), { 
    mode: 'text/html', 
    tabMode: 'indent', 
    lineNumbers: true, 
    lineWrapping: true, 
    autoCloseTags: true 
}); 

// Live preview 
editor.on("change", function() { 
    clearTimeout(delay); 
    delay = setTimeout(updatePreview, 300); 
}); 

function updatePreview() { 
    var previewFrame = document.getElementById('preview'); 
    var preview = previewFrame.contentDocument || previewFrame.contentWindow.document; 
    preview.open(); 
    preview.write(editor.getValue()); 
    preview.close(); 
} 
setTimeout(updatePreview, 300); 

function saveTextAsFile() { 
    var textToWrite = document.getElementById("code").value; 
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'}); 
    var fileNameToSaveAs = "myfile.html"; 

    var downloadLink = document.createElement("a"); 
    downloadLink.download = fileNameToSaveAs; 
    downloadLink.innerHTML = "Download File"; 
    if (window.webkitURL != null) 
    { 
     // Chrome allows the link to be clicked 
     // without actually adding it to the DOM. 
     downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); 
    } 
    else 
    { 
     // Firefox requires the link to be added to the DOM 
     // before it can be clicked. 
     downloadLink.href = window.URL.createObjectURL(textFileAsBlob); 
     downloadLink.onclick = destroyClickedElement; 
     downloadLink.style.display = "none"; 
     document.body.appendChild(downloadLink); 
    } 

    downloadLink.click();} 

function destroyClickedElement(event) { 
    document.body.removeChild(event.target);} 

function loadfile(input){ 
    var reader = new FileReader(); 
    reader.onload = function(e) { 
     document.getElementById('code').value = e.target.result;} 
    reader.readAsText(input.files[0]);} 

    var input = document.getElementById("select"); 

    function selectTheme() { 
     var theme = input.options[input.selectedIndex].innerHTML; 
     editor.setOption("theme", theme); 
    } 

    var choice = document.location.search && 
       decodeURIComponent(document.location.search.slice(1)); 
    if (choice) { 
     input.value = choice; 
     editor.setOption("theme", choice); 
    } 
</script> 
</body> 
</html> 
+0

TL; DR, 문제를 명확하게 설명하십시오. 문제가 무엇입니까? –

+0

질문이 업데이트되었습니다. 이것에 대한 해결책은 정말 도움이 될 것입니다. –

+0

콘솔에 오류가 있습니까? 더 구체적으로하십시오 –

답변

3

당신은 misusi 단순히있어 CodeMirror; 파일 콘텐츠를 할당하는 대신에, 리더에로드 될 때 value텍스트 영역 요소, 예컨대 :

reader.onload = function(e) { 
    document.getElementById('code').value = e.target.result; 
} 

중 & hellip하는 단계; 그래서처럼 CodeMirror의 API를 사용하고 에디터 인스턴스를 통해setValue() 방법을 내용을 삽입 :

reader.onload = function(e) { 
    editor.setValue(e.target.result); 
} 

CodeMirror docs for doc.setValue(content: string)를 참조하고, 여기를 보여주는 updated, working demo을합니다.

+3

오, 제발, * liveweave *, [우리] (http://jsfiddle.net/) [가지고] (http://plnkr.co/) [더 나은] (http://codepen.io/ 사용을 중지하십시오 펜 /) [도구] (http : // jsbin.co.kr /) [around] (http://tinkerbin.com/), [and] (https://shiftedit.net/) [많이] (https://c9.io/) //coderun.com/ide/) –

+0

정말 고마워요! –

+0

당신을 가장 환영합니다! –