将单字母单词移至新行

时间:2016-07-11 11:25:44

标签: javascript jquery typography

有没有办法通过javascript将单个字母的单词移动到下一行?代码来自数据库,因此我无法手动编辑它。我找到了一个找到这些单词的函数,但我不知道如何将它们放到新的行中。

<div id="flop" class="foobar">Lorem ipsum dolor sit amet, consectetur adipisicing 
    elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim 
    ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex a 
    commodo consequat. Duis aute irure dolor in reprehenderit in volue v 
    esse cillum dolore eu fugiat nulla p</div><br>
<button value="Go" onclick="foo();">Go</button>
function foo(){
    var d = document.getElementById('flop');
    var t = d.innerHTML;
    var w = t.split(' ');       

    d.innerHTML = w[0];
    var height = d.clientHeight;
    for(var i = 1; i < w.length; i++){
        d.innerHTML = d.innerHTML + ' ' + w[i];

        if(d.clientHeight > height){
            height = d.clientHeight;
          if(w[i-1].length === 1){
              console.log(w[i-1]);
          }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

在javascript中,\u000A是换行符的转义Unicode字符。

如果您已经识别出单字母单词,只需在每个单词前加上\u000A

答案 1 :(得分:0)

可能你想做这样的事情:

function foo() {
  var d = document.getElementById('flop');
  var t = d.innerHTML;
  var w = t.split(/\s/);
  var s = ''; //  <---have a var to store the new html
  d.innerHTML = ''; // <--- empty the div
  for (var i = 0; i < w.length; i++) {
    if (w[i].length === 1 && i !== w.length-1) {
      s += '<br>' + w[i] + '<br>';
    } else {
      s += ' ' + w[i];
    }
    // here append the array value to the var s which holds the 
    // new html build. Idea here is to have a check for the length
    // of the current array value to 1 then add br tags after/before
  }
  d.innerHTML = s; // finally put the new html here.
}
<div id="flop" class="foobar">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex a commodo consequat. Duis aute irure dolor in reprehenderit in volue v esse cillum dolore eu fugiat nulla p</div>
<br>
<button value="Go" onclick="foo();">Go</button>

相关问题