2013-04-13 45 views
0

現在,我正在嘗試創建所見即所得的HTML編輯器,並且需要在正在編輯的div旁邊顯示contentEditable div的源代碼。我試圖自動同步這兩個元素,但我還不確定最好的方法是什麼。在contentEditable div旁顯示源代碼

<div contentEditable ="true" id = "showSourceCodeForThis">test 1</div> 
<input type = "text" id = "showSourceCodeHere"></input> 

每當contentEditable div更新時,我希望顯示的源代碼也自動更新,反之亦然。是否有可能將contenteditable div的內容與顯示contenteditable div的源代碼的文本框同步?

+0

http://stackoverflow.com/a/8694125/96100 –

回答

0

這是一個可行的解決方案:http://jsfiddle.net/sDdN3/14/

HTML:

<div contentEditable ="true" id = "showSourceCodeForThis">test 1</div> 
<input type = "text" id = "showSourceCodeHere"></input> 

的JavaScript:

function test(){ 
    var divs = document.getElementById('showSourceCodeForThis'); 
     divs.onkeyup=function(event){ 
      document.getElementById('showSourceCodeHere').value = document.getElementById('showSourceCodeForThis').innerHTML; 
     } 
} 

function test2(){ 
    var divs = document.getElementById('showSourceCodeHere'); 
     divs.onkeyup=function(event){ 
      document.getElementById('showSourceCodeForThis').innerHTML = document.getElementById('showSourceCodeHere').value; 
     } 
} 

test(); 
test2();