小编典典

寻找换行

javascript

假设我在一行中有一些随机的文本块。像这样

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

但是无论出于何种原因(包含元素的宽度设置,使用文本缩放等),在查看器的屏幕上它都显示为两行或更多行。

Lorem ipsum dolor sit amet,

consectetur adipiscing elit.

要么

Lorem ipsum dolor sit

amet, consectetur

adipiscing elit.

有没有办法通过JavaScript找出发生换行的地方?

$('p').text()$('p').html()返回Lorem ipsum dolor sit amet, consectetur adipiscing elit.而不管文本如何显示。


阅读 461

收藏
2020-05-01

共1个答案

小编典典

这就是我最终使用的(随意批评和复制以作恶用)。

首先,当编辑来自用户时,将其拆分为$(editableElement).lineText(userInput)

jQuery.fn.lineText = function (userInput) {
   var a = userInput.replace(/\n/g, " \n<br/> ").split(" ");
   $.each(a, function(i, val) { 
      if(!val.match(/\n/) && val!="") a[i] = '<span class="word-measure">' + val + '</span>';
   });
   $(this).html(a.join(" "));
};

替换换行的原因是,编辑文本框中填充了$(editableElement).text(),它会忽略<br/>标签,但出于排版目的,它们仍将更改显示屏中下一行的高度。这不是最初目标的一部分,只是悬而未决的结果。

当我需要提取带格式的文本时,请致电$(editableElement).getLines(),其中

jQuery.fn.getLines = function (){
   var count = $(this).children(".word-measure").length;
   var lineAcc = [$(this).children(".word-measure:eq(0)").text()];
   var textAcc = [];
   for(var i=1; i<count; i++){
      var prevY = $(this).children(".word-measure:eq("+(i-1)+")").offset().top;
      if($(this).children(".word-measure:eq("+i+")").offset().top==prevY){
         lineAcc.push($(this).children(".word-measure:eq("+i+")").text());
   } else {
     textAcc.push({text: lineAcc.join(" "), top: prevY});
     lineAcc = [$(this).children(".word-measure:eq("+i+")").text()];
   }
   }
   textAcc.push({text: lineAcc.join(" "), top: $(this).children(".word-measure:last").offset().top});
   return textAcc;
};

最终结果是一列哈希,每个哈希包含内容和一行文本的垂直偏移量。

[{"text":"Some dummy set to","top":363},
 {"text":"demonstrate...","top":382},
 {"text":"The output of this","top":420},
 {"text":"wrap-detector.","top":439}]

如果我只想要无格式的文本,$(editableElement).text()仍然会返回

"Some dummy set to demonstrate... The output of this wrap-detector."
2020-05-01