包裹跨度中的每一行

时间:2017-04-03 19:12:08

标签: javascript jquery html css

我正在试图弄清楚如何在一个范围内包装每行副本。例如,如果我有一个如下元素:

.body-copy {
  position: relative;
  width: 100%;
  height: auto
}
<div class="body-copy">
  Lorem ipsum dolor sit amet, consectetur adipiscing 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 ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.
</div>

因此文本填充了它的容器宽度,我需要在文档加载,窗口加载和窗口大小调整的span中包装每行副本。如果这是可能的?对此有任何建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

好的,所以这是一个混乱但功能性的方式来做你要求的。这样做是使用隐藏的div来测量原始的宽度,因为我们逐个添加单词。然后,一旦达到宽度阈值,我们就会创建一个新的span元素,其中包含到目前为止收集的单词。洗净。冲洗。重复。最后,我们挖掘剩下的单词并将它们添加到自己的span,并用新的HTML替换原始文本。您可以在文档加载或窗口调整大小时随时使用wordWrap()功能。我已经为span元素添加了一些边框,这样您就可以轻松查看标记的应用位置。

$(document).ready(function() {
  wordWrap();
});

function wordWrap() {
  var bdy = $(".body-copy");
  var text = $(bdy).text();
  var html = $(bdy).html();
  var bWidth = $(bdy).width();
  var words = text.split(" ");
  var span = "";
  var word = "";
  var allSpans = "";
  var lastWord = "";
  $(words).each(function(i, w) {
    if (lastWord != "") {
      w = lastWord + " "+ w ;
      lastWord = "";
    };
    word = w + " ";
    span = span + word;
    $(".body-copy-two").append(word);
    if ($(".body-copy-two").width() >= bWidth) {
      var wLen = word.length;
      span = span.slice(0, -wLen);
      lastWord = w + " ";
      allSpans = allSpans + "<span>" + $.trim(span) + "</span>";
      $(".body-copy-two").html("");
      span = "";
      word = "";
    }
  });
  var lastSpan = "<span>" + $(".body-copy-two").text() + "</span>";
  $(bdy).html(allSpans + lastSpan);
}
.body-copy {
  position: relative;
  width: 100%;
  height: auto
}

.body-copy-two {
  position: absolute;
  visibility: hidden;
}

.body-copy span {
  border: 1px solid black;
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body-copy">
  Lorem ipsum dolor sit amet, consectetur adipiscing 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 ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labour.
</div>
<div class="body-copy-two"></div>