使用Javascript在多行中拆分长句

时间:2015-03-06 12:17:38

标签: javascript

我的mysql字段中有一个长句子,在我的jquery表格文本中显示如下:

In the aftermath of her sudden Vancouver celebrity, she appeared as the cover girl on Playboy magazine's October 1989 issue. At that point she decided to live in Los Angeles to further pursue her modeling career. Playboy subsequently chose her as Playmate of the Month in their February 1990 issue, in which she appeared in the centerfold photo.

exceeds limit

我希望在12个单词之后将长句分成多行(例如)

In the aftermath of her sudden Vancouver celebrity, she appeared as the
cover girl on Playboy magazine's October 1989 issue. At that point she 
decided to live in Los Angeles to further pursue her modeling career. Playboy 
subsequently chose her as Playmate of the Month in their February 1990
issue, in which she appeared in the centerfold photo.

我可以使用哪些JavaScript代码?

2 个答案:

答案 0 :(得分:1)

嗨,这是我使用javascript的代码,请查看演示。如果您有问题,请告诉我。我分成了12个

var paragraph = "In the aftermath of her sudden Vancouver celebrity, she appeared as the cover girl on Playboy magazine's October 1989 issue. At that point she decided to live in Los Angeles to further pursue her modeling career. Playboy subsequently chose her as Playmate of the Month in their February 1990 issue, in which she appeared in the centerfold photo. Heloo Im van testing this code";

$(function(){
var data = paragraph.split(' ');
  var x=0,y=0,iterator=12;
    var xarray =  data.length;
    for(var i = iterator;i < xarray; i +=iterator){
      $('#container').append(paragraph.split(/\s+/).slice(x,i).join(" ")+"<br />");
      y = xarray-i;  
      x = i;
        if(y<iterator){
         $('#container').append(paragraph.split(/\s+/).slice(x,i+y).join(" ")+"<br />");
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>

答案 1 :(得分:0)

我会将word-wrap: break-word添加到单元格并将table-layout: fixed添加到表格中,然后您可以指定该列的宽度,文本将换行到多行。

table {
    table-layout: fixed;
}

td {
    word-wrap: break-word;
}

修改

如果给单元格一个宽度,内容将自动换行到多行。您可以为单元格指定一个类,也可以使用nth-child

对其进行定位
td:nth-child(2) {
    width: 300px;
}

fiddle