2014-09-19 72 views
0

當您在以下代碼片段中單擊背景時,將創建一個contenteditable<span>。嘗試寫「Hello World」。 空格導致換行符。爲什麼?contenteditable中的空格會導致換行

如何使可用空間中的空格不再導致任何換行符?

window.onload = function() { 
 
     var container = document.createElement("div"), 
 
     wrapper = document.createElement("div"); 
 

 
     container.style.position = "absolute"; 
 
     wrapper.style.position = "relative"; 
 
     container.appendChild(wrapper); 
 
     document.body.appendChild(container); 
 

 
     window.onclick = function(e) { 
 
     var tb = document.createElement('span'); 
 
     tb.contentEditable = true; 
 
     tb.style.position = 'absolute'; 
 
     tb.style.top = e.clientY + 'px'; 
 
     tb.style.left = e.clientX + 'px'; 
 
     wrapper.appendChild(tb); 
 
     tb.focus(); 
 
     } 
 
    }

回答

1

使用CSS white-space:pre

「空白的序列被保留,線僅在源極和在<br>元件換行符斷裂。」

https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

只需添加一行:

tb.style.whiteSpace = 'pre'; 

E.G:

window.onload = function() { 
 
     var container = document.createElement("div"), 
 
     wrapper = document.createElement("div"); 
 

 
     container.style.position = "absolute"; 
 
     wrapper.style.position = "relative"; 
 
     container.appendChild(wrapper); 
 
     document.body.appendChild(container); 
 

 
     window.onclick = function(e) { 
 
     var tb = document.createElement('span'); 
 
     tb.contentEditable = true; 
 
     tb.style.position = 'absolute'; 
 
     tb.style.top = e.clientY + 'px'; 
 
     tb.style.left = e.clientX + 'px'; 
 
     tb.style.whiteSpace = 'pre'; // < here 
 
     wrapper.appendChild(tb); 
 
     tb.focus(); 
 
     } 
 
    }

+0

感謝@Moob!我有一個相關的非常棘手的問題在這裏:http://stackoverflow.com/questions/27185427/unwanted-linebreak-in-contenteditable-div 你有什麼想法? – Basj 2014-11-28 09:29:12

相關問題