목차
하지만 여러 줄 텍스트의 오버플로를 어떻게 처리할까요?
웹 프론트엔드 JS 튜토리얼 v-clamp 명령어를 캡슐화하여 여러 줄의 텍스트 오버플로를 처리합니다.

v-clamp 명령어를 캡슐화하여 여러 줄의 텍스트 오버플로를 처리합니다.

Oct 26, 2018 pm 03:24 PM
css javascript

이 글의 내용은 v-clamp 명령을 캡슐화하여 여러 줄의 텍스트 오버플로를 처리하는 내용입니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

최근 프로젝트를 진행하면서 div의 텍스트를 두 줄로 표시해야 한다는 요구 사항을 만났습니다. div의 너비가 넘치면 줄임표가 표시됩니다. 우리 모두는 한 줄 텍스트의 오버플로 문제에 대해 잘 알고 있습니다. 다음 CSS 속성만 추가하면 괜찮습니다.

  overflow: hidden;
  white-space: nowrap; //段落中文本不换行
  text-overflow: ellipsis;
로그인 후 복사

하지만 여러 줄 텍스트의 오버플로를 어떻게 처리할까요?

정보를 확인한 결과 아직 방법이 있다는 것을 알았습니다.

WebKit 브라우저나 모바일 터미널(WebKit 코어가 있는 대부분의 브라우저)에서 페이지를 구현하는 것은 비교적 간단합니다. WebKit의 CSS 확장 속성을 직접 사용할 수 있습니다. 개인 속성) )-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 브라우저에서는 작동하지 않습니다.

호환성 문제를 해결하기 위해 이 문제를 아주 잘 해결해 주는 클램프.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&#39;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 {
            &#39;original&#39;: originalText,
            &#39;clamped&#39;: clampedText
          };
        }

       clamp(el,{clamp: 2}) 


  }
})
로그인 후 복사

실제로는 매우 간단합니다. 클램프.js에서 함수를 옮기기만 하면 됩니다. 그러면 다음과 같이 사용할 수 있습니다:

  <div class="txt" v-clamp>很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板很抱歉!没有搜索到相关模板</div>
로그인 후 복사

위 내용은 v-clamp 명령어를 캡슐화하여 여러 줄의 텍스트 오버플로를 처리합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Vue에서 부트 스트랩을 사용하는 방법 Vue에서 부트 스트랩을 사용하는 방법 Apr 07, 2025 pm 11:33 PM

vue.js에서 bootstrap 사용은 5 단계로 나뉩니다 : Bootstrap 설치. main.js.의 부트 스트랩 가져 오기 부트 스트랩 구성 요소를 템플릿에서 직접 사용하십시오. 선택 사항 : 사용자 정의 스타일. 선택 사항 : 플러그인을 사용하십시오.

HTML, CSS 및 JavaScript의 역할 : 핵심 책임 HTML, CSS 및 JavaScript의 역할 : 핵심 책임 Apr 08, 2025 pm 07:05 PM

HTML은 웹 구조를 정의하고 CSS는 스타일과 레이아웃을 담당하며 JavaScript는 동적 상호 작용을 제공합니다. 세 사람은 웹 개발에서 의무를 수행하고 화려한 웹 사이트를 공동으로 구축합니다.

부트 스트랩에 분할 라인을 작성하는 방법 부트 스트랩에 분할 라인을 작성하는 방법 Apr 07, 2025 pm 03:12 PM

부트 스트랩 분할 라인을 만드는 두 가지 방법이 있습니다 : 태그를 사용하여 수평 분할 라인이 생성됩니다. CSS 테두리 속성을 사용하여 사용자 정의 스타일 분할 라인을 만듭니다.

HTML, CSS 및 JavaScript 이해 : 초보자 안내서 HTML, CSS 및 JavaScript 이해 : 초보자 안내서 Apr 12, 2025 am 12:02 AM

WebDevelopmentReliesonHtml, CSS 및 JavaScript : 1) HtmlStructuresContent, 2) CSSSTYLESIT, 및 3) JAVASCRIPTADDSINGINTERACTIVITY, BASISOFMODERNWEBEXPERIENCES를 형성합니다.

부트 스트랩에 사진을 삽입하는 방법 부트 스트랩에 사진을 삽입하는 방법 Apr 07, 2025 pm 03:30 PM

Bootstrap에 이미지를 삽입하는 방법에는 여러 가지가 있습니다. HTML IMG 태그를 사용하여 이미지를 직접 삽입하십시오. 부트 스트랩 이미지 구성 요소를 사용하면 반응 형 이미지와 더 많은 스타일을 제공 할 수 있습니다. 이미지 크기를 설정하고 IMG-Fluid 클래스를 사용하여 이미지를 적응할 수 있도록하십시오. IMG 통과 클래스를 사용하여 테두리를 설정하십시오. 둥근 모서리를 설정하고 IMG 라운드 클래스를 사용하십시오. 그림자를 설정하고 그림자 클래스를 사용하십시오. CSS 스타일을 사용하여 이미지를 조정하고 배치하십시오. 배경 이미지를 사용하여 배경 이미지 CSS 속성을 사용하십시오.

부트 스트랩을위한 프레임 워크를 설정하는 방법 부트 스트랩을위한 프레임 워크를 설정하는 방법 Apr 07, 2025 pm 03:27 PM

부트 스트랩 프레임 워크를 설정하려면 다음 단계를 따라야합니다. 1. CDN을 통해 부트 스트랩 파일 참조; 2. 자신의 서버에서 파일을 다운로드하여 호스팅하십시오. 3. HTML에 부트 스트랩 파일을 포함; 4. 필요에 따라 Sass/Less를 컴파일하십시오. 5. 사용자 정의 파일을 가져옵니다 (선택 사항). 설정이 완료되면 Bootstrap의 그리드 시스템, 구성 요소 및 스타일을 사용하여 반응 형 웹 사이트 및 응용 프로그램을 만들 수 있습니다.

부트 스트랩 크기를 조정하는 방법 부트 스트랩 크기를 조정하는 방법 Apr 07, 2025 pm 03:18 PM

부트 스트랩에서 요소의 크기를 조정하려면 다음을 포함하여 차원 클래스를 사용할 수 있습니다.

부트 스트랩 버튼을 사용하는 방법 부트 스트랩 버튼을 사용하는 방법 Apr 07, 2025 pm 03:09 PM

부트 스트랩 버튼을 사용하는 방법? 부트 스트랩 CSS를 소개하여 버튼 요소를 만들고 부트 스트랩 버튼 클래스를 추가하여 버튼 텍스트를 추가하십시오.

See all articles