搜尋
首頁web前端js教程透過封裝一個v-clamp的指令處理多行文字的溢出

這篇文章帶給大家的內容是關於透過封裝一個v-clamp的指令處理多行文字的溢出,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

最近做專案時,遇到了一個需求:要求div里文字在兩行顯示,div的寬度是固定的,如果溢出的話就顯示省略號。單行文字的溢出問題,我們都很熟悉,只要加入以下css屬性就ok:

  overflow: hidden;
  white-space: nowrap; //段落中文本不换行
  text-overflow: ellipsis;

但是多行文字的溢出怎麼處理呢?

查了資料之後發現還是有辦法的

在WebKit瀏覽器或行動端(絕大部分是WebKit內核的瀏覽器)的頁面實作比較簡單,可以直接使用WebKit的CSS擴充屬性(WebKit是私有屬性)-webkit-line-clamp ;注意:這是一個 不規範的屬性(unsupported WebKit property),它沒有出現在 CSS 規範草案中。 -webkit-line-clamp用來限制在一個區塊元素顯示的文字的行數。為了實現該效果,它需要組合其他的WebKit屬性。

我們用程式碼即可實現:

    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

但是這樣處理會遇到相容性問題,在Firefox瀏覽器上就不起作用。

為了解決相容性問題,有一個clamp.js[https://www.npmjs.com/package...]很好的解決這個問題。

為了更好的跟Vue結合,今天我們就封裝一個v-clamp的指令,來方便的解決這個問題。

// 注册一个全局自定义指令 `v-clamp`
Vue.directive('clamp', {
  // 当被绑定的元素插入到 DOM 中时……
  update: function (el, binding) {
      function clamp(element, options) {
          options = options || {};
      
          var self = this,
            win = window,
            opt = {
              clamp: options.clamp || 2,
              useNativeClamp: typeof(options.useNativeClamp) != 'undefined' ? options.useNativeClamp : true,
              splitOnChars: options.splitOnChars || ['.', '-', '–', '—', ' '], //Split on sentences (periods), hypens, en-dashes, em-dashes, and words (spaces).
              animate: options.animate || false,
              truncationChar: options.truncationChar || '…',
              truncationHTML: options.truncationHTML
            },
      
            sty = element.style,
            originalText = element.innerHTML,
      
            supportsNativeClamp = typeof(element.style.webkitLineClamp) != 'undefined',
            clampValue = opt.clamp,
            isCSSValue = clampValue.indexOf && (clampValue.indexOf('px') > -1 || clampValue.indexOf('em') > -1),
            truncationHTMLContainer;
      
          if (opt.truncationHTML) {
            truncationHTMLContainer = document.createElement('span');
            truncationHTMLContainer.innerHTML = opt.truncationHTML;
          }
      
      
          // UTILITY FUNCTIONS __________________________________________________________
      
          /**
           * Return the current style for an element.
           * @param {HTMLElement} elem The element to compute.
           * @param {string} prop The style property.
           * @returns {number}
           */
          function computeStyle(elem, prop) {
            if (!win.getComputedStyle) {
              win.getComputedStyle = function(el, pseudo) {
                this.el = el;
                this.getPropertyValue = function(prop) {
                  var re = /(\-([a-z]){1})/g;
                  if (prop == 'float') prop = 'styleFloat';
                  if (re.test(prop)) {
                    prop = prop.replace(re, function() {
                      return arguments[2].toUpperCase();
                    });
                  }
                  return el.currentStyle && el.currentStyle[prop] ? el.currentStyle[prop] : null;
                };
                return this;
              };
            }
      
            return win.getComputedStyle(elem, null).getPropertyValue(prop);
          }
      
          /**
           * Returns the maximum number of lines of text that should be rendered based
           * on the current height of the element and the line-height of the text.
           */
          function getMaxLines(height) {
            var availHeight = height || element.clientHeight,
              lineHeight = getLineHeight(element);
      
            return Math.max(Math.floor(availHeight / lineHeight), 0);
          }
      
          /**
           * Returns the maximum height a given element should have based on the line-
           * height of the text and the given clamp value.
           */
          function getMaxHeight(clmp) {
            var lineHeight = getLineHeight(element);
            return lineHeight * clmp;
          }
      
          /**
           * Returns the line-height of an element as an integer.
           */
          function getLineHeight(elem) {
            var lh = computeStyle(elem, 'line-height');
            if (lh == 'normal') {
              // Normal line heights vary from browser to browser. The spec recommends
              // a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff.
              lh = parseInt(computeStyle(elem, 'font-size')) * 1.2;
            }
            return parseInt(lh);
          }
      
      
          // MEAT AND POTATOES (MMMM, POTATOES...) ______________________________________
          var splitOnChars = opt.splitOnChars.slice(0),
            splitChar = splitOnChars[0],
            chunks,
            lastChunk;
      
          /**
           * Gets an element's last child. That may be another node or a node's contents.
           */
          function getLastChild(elem) {
            //Current element has children, need to go deeper and get last child as a text node
            if (elem.lastChild.children && elem.lastChild.children.length > 0) {
              return getLastChild(Array.prototype.slice.call(elem.children).pop());
            }
            //This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying
            else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue === '' || elem.lastChild.nodeValue == opt.truncationChar) {
              elem.lastChild.parentNode.removeChild(elem.lastChild);
              return getLastChild(element);
            }
            //This is the last child we want, return it
            else {
              return elem.lastChild;
            }
          }
      
          /**
           * Removes one character at a time from the text until its width or
           * height is beneath the passed-in max param.
           */
          function truncate(target, maxHeight) {
            if (!maxHeight) {
              return;
            }
      
            /**
             * Resets global variables.
             */
            function reset() {
              splitOnChars = opt.splitOnChars.slice(0);
              splitChar = splitOnChars[0];
              chunks = null;
              lastChunk = null;
            }
      
            var nodeValue = target.nodeValue.replace(opt.truncationChar, '');
      
            //Grab the next chunks
            if (!chunks) {
              //If there are more characters to try, grab the next one
              if (splitOnChars.length > 0) {
                splitChar = splitOnChars.shift();
              }
              //No characters to chunk by. Go character-by-character
              else {
                splitChar = '';
              }
      
              chunks = nodeValue.split(splitChar);
            }
      
            //If there are chunks left to remove, remove the last one and see if
            // the nodeValue fits.
            if (chunks.length > 1) {
              // console.log('chunks', chunks);
              lastChunk = chunks.pop();
              // console.log('lastChunk', lastChunk);
              applyEllipsis(target, chunks.join(splitChar));
            }
            //No more chunks can be removed using this character
            else {
              chunks = null;
            }
      
            //Insert the custom HTML before the truncation character
            if (truncationHTMLContainer) {
              target.nodeValue = target.nodeValue.replace(opt.truncationChar, '');
              element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
            }
      
            //Search produced valid chunks
            if (chunks) {
              //It fits
              if (element.clientHeight = 0 && splitChar !== '') {
                  applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk);
                  chunks = null;
                }
                //Finished!
                else {
                  return element.innerHTML;
                }
              }
            }
            //No valid chunks produced
            else {
              //No valid chunks even when splitting by letter, time to move
              //on to the next node
              if (splitChar === '') {
                applyEllipsis(target, '');
                target = getLastChild(element);
      
                reset();
              }
            }
      
            //If you get here it means still too big, let's keep truncating
            if (opt.animate) {
              setTimeout(function() {
                truncate(target, maxHeight);
              }, opt.animate === true ? 10 : opt.animate);
            } else {
              return truncate(target, maxHeight);
            }
          }
      
          function applyEllipsis(elem, str) {
            elem.nodeValue = str + opt.truncationChar;
          }
      
      
          // CONSTRUCTOR ________________________________________________________________
      
          if (clampValue == 'auto') {
            clampValue = getMaxLines();
          } else if (isCSSValue) {
            clampValue = getMaxLines(parseInt(clampValue));
          }
      
          var clampedText;
          if (supportsNativeClamp && opt.useNativeClamp) {
            sty.overflow = 'hidden';
            sty.textOverflow = 'ellipsis';
            sty.webkitBoxOrient = 'vertical';
            sty.display = '-webkit-box';
            sty.webkitLineClamp = clampValue;
      
            if (isCSSValue) {
              sty.height = opt.clamp + 'px';
            }
          } else {
            var height = getMaxHeight(clampValue);
            if (height <p>其實很簡單,只是把clamp.js中的函數搬過來了。然後就可以這樣來使用:</p><pre class="brush:php;toolbar:false">  <div>很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板</div>

以上是透過封裝一個v-clamp的指令處理多行文字的溢出的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除
JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

如何安裝JavaScript?如何安裝JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

在Quartz中如何在任務開始前發送通知?在Quartz中如何在任務開始前發送通知?Apr 04, 2025 pm 09:24 PM

如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...

在JavaScript中,如何在構造函數中獲取原型鏈上函數的參數?在JavaScript中,如何在構造函數中獲取原型鏈上函數的參數?Apr 04, 2025 pm 09:21 PM

在JavaScript中如何獲取原型鏈上函數的參數在JavaScript編程中,理解和操作原型鏈上的函數參數是常見且重要的任�...

微信小程序webview中Vue.js動態style位移失效是什麼原因?微信小程序webview中Vue.js動態style位移失效是什麼原因?Apr 04, 2025 pm 09:18 PM

在微信小程序web-view中使用Vue.js動態style位移失效的原因分析在使用Vue.js...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具