v-clamp 命令をカプセル化して複数行のテキスト オーバーフローを処理する
この記事の内容は、v-clamp 命令をカプセル化することによる複数行のテキストのオーバーフローの処理に関するものです。必要な方は参考にしていただければ幸いです。
最近、あるプロジェクトに取り組んでいたときに、div 内のテキストを 2 行で表示する必要があるという要件に遭遇しました。div の幅がオーバーフローした場合、省略記号が表示されます。表示されます。単一行テキストのオーバーフローの問題はよく知られていますが、次の css 属性を追加するだけで問題は解決します。
overflow: hidden; white-space: nowrap; //段落中文本不换行 text-overflow: ellipsis;
しかし、複数行テキストのオーバーフローにどう対処すればよいでしょうか。
情報を確認した結果、まだ方法があることがわかりました。
WebKit ブラウザまたはモバイル端末 (WebKit コアを備えたほとんどのブラウザ) でページを実装するのは比較的簡単です。 WebKit 直接 CSS 拡張プロパティ (WebKit はプライベート プロパティ)-webkit-line-clamp ;注: これはサポートされていない WebKit プロパティであり、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 <= maxHeight) { //There's still more characters to try splitting on, not quite done yet if (splitOnChars.length >= 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 <= element.clientHeight) { console.log(getLastChild(element)); clampedText = truncate(getLastChild(element), height); } } return { 'original': originalText, 'clamped': clampedText }; } clamp(el,{clamp: 2}) } })
実際には、clamp.js 内の関数を移動するだけです。次に、次のように使用できます:
<div class="txt" v-clamp>很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板</div>
以上がv-clamp 命令をカプセル化して複数行のテキスト オーバーフローを処理するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









vue.jsでBootstrapを使用すると、5つのステップに分かれています。ブートストラップをインストールします。 main.jsにブートストラップをインポートしますブートストラップコンポーネントをテンプレートで直接使用します。オプション:カスタムスタイル。オプション:プラグインを使用します。

HTMLはWeb構造を定義し、CSSはスタイルとレイアウトを担当し、JavaScriptは動的な相互作用を提供します。 3人はWeb開発で職務を遂行し、共同でカラフルなWebサイトを構築します。

ブートストラップスプリットラインを作成するには2つの方法があります。タグを使用して、水平方向のスプリットラインを作成します。 CSS Borderプロパティを使用して、カスタムスタイルのスプリットラインを作成します。

webdevelopmentReliesOnhtml、css、andjavascript:1)htmlStructuresContent、2)cssStylesit、および3)Javascriptaddsinteractivity、形成、

ブートストラップボタンの使用方法は?ブートストラップCSSを導入してボタン要素を作成し、ブートストラップボタンクラスを追加してボタンテキストを追加します

Bootstrapフレームワークをセットアップするには、次の手順に従う必要があります。1。CDNを介してブートストラップファイルを参照してください。 2。独自のサーバーでファイルをダウンロードしてホストします。 3。HTMLにブートストラップファイルを含めます。 4.必要に応じてSASS/LESSをコンパイルします。 5。カスタムファイルをインポートします(オプション)。セットアップが完了したら、Bootstrapのグリッドシステム、コンポーネント、スタイルを使用して、レスポンシブWebサイトとアプリケーションを作成できます。

ブートストラップに画像を挿入する方法はいくつかあります。HTMLIMGタグを使用して、画像を直接挿入します。ブートストラップ画像コンポーネントを使用すると、レスポンシブ画像とより多くのスタイルを提供できます。画像サイズを設定し、IMG-Fluidクラスを使用して画像を適応可能にします。 IMGボーダークラスを使用して、境界線を設定します。丸い角を設定し、IMGラウンドクラスを使用します。影を設定し、影のクラスを使用します。 CSSスタイルを使用して、画像をサイズ変更して配置します。背景画像を使用して、背景イメージCSSプロパティを使用します。
