2014-09-19 473 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