满足的空白导致换行

时间:2014-09-19 10:44:32

标签: javascript css html5 css3 contenteditable

当您点击以下代码段中的背景时,会创建contenteditable <span>。尝试写“Hello World”。 空白会导致换行。为什么?

如何在可疑范围内使空格不再导致任何换行?

    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 个答案:

答案 0 :(得分: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();
      }
    }

相关问题