


Gérer le débordement de texte sur plusieurs lignes en encapsulant une instruction v-clamp
Le contenu de cet article concerne le traitement du débordement de texte multiligne en encapsulant une instruction v-clamp. Il a une certaine valeur de référence. Les amis dans le besoin peuvent s'y référer.
Lorsque je travaillais sur un projet récemment, j'ai rencontré une exigence : le texte du div doit être affiché sur deux lignes. La largeur du div est fixe. S'il déborde, des points de suspension seront affichés. affiché. Nous connaissons tous le problème de débordement de texte sur une seule ligne. Ajoutez simplement les attributs CSS suivants et tout ira bien :
overflow: hidden; white-space: nowrap; //段落中文本不换行 text-overflow: ellipsis;
Mais comment gérer le débordement de texte sur plusieurs lignes ?
Après avoir vérifié les informations, j'ai découvert qu'il existe encore un moyen
Il est relativement simple d'implémenter la page dans le navigateur WebKit ou le terminal mobile (la plupart des navigateurs avec le noyau WebKit), et vous pouvez utiliser WebKit directement les propriétés étendues CSS (WebKit est une propriété privée) -webkit-line-clamp ;Remarque : il s'agit d'une propriété WebKit non prise en charge et n'apparaît pas en CSS dans le projet de cahier des charges. -webkit-line-clamp est utilisé pour limiter le nombre de lignes de texte affichées dans un élément de bloc. Pour obtenir cet effet, il doit être combiné avec d'autres propriétés WebKit.
On peut y parvenir avec le code suivant :
overflow : hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
Cependant, cette méthode rencontrera des problèmes de compatibilité et ne fonctionnera pas sur le navigateur Firefox.
Afin de résoudre le problème de compatibilité, il existe clamp.js[https://www.npmjs.com/package...] qui résout très bien ce problème.
Afin de mieux s'intégrer à Vue, nous allons aujourd'hui encapsuler une instruction v-clamp pour résoudre facilement ce problème.
// 注册一个全局自定义指令 `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}) } })
C'est en fait très simple, il suffit de déplacer les fonctions dans clamp.js. Ensuite, vous pouvez l'utiliser comme ceci :
<div class="txt" v-clamp>很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板</div>
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

AI Hentai Generator
Générez AI Hentai gratuitement.

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

L'utilisation de bootstrap dans vue.js est divisée en cinq étapes: installer bootstrap. Importer un bootstrap dans main.js. Utilisez le composant bootstrap directement dans le modèle. Facultatif: style personnalisé. Facultatif: utilisez des plug-ins.

HTML définit la structure Web, CSS est responsable du style et de la mise en page, et JavaScript donne une interaction dynamique. Les trois exercent leurs fonctions dans le développement Web et construisent conjointement un site Web coloré.

Il existe deux façons de créer une ligne divisée bootstrap: en utilisant la balise, qui crée une ligne divisée horizontale. Utilisez la propriété CSS Border pour créer des lignes de fractionnement de style personnalisées.

WebDevelopmentReliesOnHTML, CSS, etjavascript: 1) HTMLSTRUCTURESCONTENT, 2) CSSSTYLESIT, et3) JavascriptAdddsInterActivity, Forming TheasisofmodernweBEBExperiences.

Pour configurer le framework Bootstrap, vous devez suivre ces étapes: 1. Référez le fichier bootstrap via CDN; 2. Téléchargez et hébergez le fichier sur votre propre serveur; 3. Incluez le fichier bootstrap dans HTML; 4. Compiler les sass / moins au besoin; 5. Importer un fichier personnalisé (facultatif). Une fois la configuration terminée, vous pouvez utiliser les systèmes, composants et styles de grille de Bootstrap pour créer des sites Web et des applications réactifs.

Pour ajuster la taille des éléments dans Bootstrap, vous pouvez utiliser la classe de dimension, qui comprend: ajuster la largeur: .col-, .w-, .mw-ajustement Hauteur: .h-, .min-h-, .max-h-

Comment utiliser le bouton bootstrap? Introduisez Bootstrap CSS pour créer des éléments de bouton et ajoutez la classe de bouton bootstrap pour ajouter du texte du bouton

Il existe plusieurs façons d'insérer des images dans Bootstrap: insérer directement les images, en utilisant la balise HTML IMG. Avec le composant d'image bootstrap, vous pouvez fournir des images réactives et plus de styles. Définissez la taille de l'image, utilisez la classe IMG-FLUID pour rendre l'image adaptable. Réglez la bordure en utilisant la classe IMG-border. Réglez les coins arrondis et utilisez la classe Roundée IMG. Réglez l'ombre, utilisez la classe Shadow. Redimensionner et positionner l'image, en utilisant le style CSS. À l'aide de l'image d'arrière-plan, utilisez la propriété CSS d'image d'arrière-plan.
