簡體   English   中英

沒有固定高度時,如何在jquery中檢測換行?

[英]How to detect a line-break in jquery when there is no fixed height?

我需要我的插件來檢測元素的換行符,這是代碼:

$.fn.inlineOffset = function (){
    if ($(this).css('text-indent') == '0px' && $(this).height() != 17) {
      var el = $('<i/>').css('display', 'inline').insertBefore(this[0]);
          pos = el.offset();
      el.remove();
      return pos;
    }
    else {
      var pos = $(this).offset()
      return pos;
    }
  };

如您所見,它僅在元素的高度為17px時才有效。 但是,如果我需要設置不同的高度怎么辦? 我需要此解決方案,因為如果嘗試在新行的第一個字母之前添加元素,該元素將顯示在其父級的左上角,並且僅在文本行斷開時才需要添加。

我使用的一種方法是通過將文本在空間上拆分為數組並將aray與span標簽連接,將所有span循環以檢查位置,從而將span中的每個單詞包裝起來。 當頂部增加時,您發現換行符

我想出了一個解決方案。 在這里嘗試一下: http : //jsfiddle.net/6V2Pd/1/關鍵點是以下代碼行:

//here we get the calculated height of the text element when white space is nowrap (single line)
$target.css('white-space', 'nowrap');
var nowrapHeight = $target.height();

//here we get the calc. height when white space is normal (breaks are allowed)
$target.css('white-space', 'normal');
var normalwrapHeight = $target.height();

// here we are going to compare the two values and come to a conclusion
// if nowrapHeight != normalwrapHeight => it's a multiline text
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM