簡體   English   中英

如何檢查線鉗是否啟用?

[英]How can I check whether line-clamp is enabled?

我在一個跨度中有一個動態文本。 我想使用line-clamp: 2

在那種情況下,最多。 2 行文本和 rest 被截斷為

適用於:

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

我的問題:如果內容被截斷,則應顯示工具提示。 如何檢測文本是否被夾住?

元素的高度相同, innerHTML相同......我沒有進一步的想法......

您可以檢查元素 scrollHeight 是否超過 clientHeight:

function multiLineOverflows() {
    const el = this._element.nativeElement;
    return el.scrollHeight > el.clientHeight;
}

可以通過比較“ scrollHeight ”元素的scrollHeightclientHeight來通過javascript檢測 CSS line-clamp

元素的“真實”高度被overflow: hidden CSS 屬性裁剪,但DOM 屬性scrollHeight將報告完整高度,而clientHeight報告渲染高度。

在此處輸入圖片說明

下面的示例顯示了一個夾住的文本。
嘗試將其懸停以查看檢測是否已記錄。 (文本可編輯)

 const isTextClamped = elm => elm.scrollHeight > elm.clientHeight const onMouseEnter = elm => { console.clear() console.log( isTextClamped(elm) ) }
 p { width: 200px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; resize: both; /* allowing resize for this demo only */ }
 <p contenteditable spellcheck="false" onmouseenter="onMouseEnter(this)"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p>

👉 這是一個Codepen現場演示

這是 NextJS、React、Typescript 和 Tailwind 的解決方案,包括一個用於“閱讀更多...”的按鈕,該按鈕會在文本被限制時出現。

代碼前的說明:

這是一個作為道具發布的反應組件(可以是其他任何東西)。 該帖子包含我們應該顯示的內容,有 4 行限制,直到用戶單擊“閱讀更多...”。

content ref(useRef 掛鈎)包含對應在其中顯示內容的內容 div 的引用。 首先 useState 掛鈎持有 state isClamped:如果內容被限制則為真,否則為假。 第二個 useState 包含 state isExpanded:如果用戶單擊“閱讀更多...”則為 true,否則為 false。 然后,useEffect 掛鈎(由於設置了空數組而僅在掛載時調用)將事件偵聽器添加到 window 調整大小(這可能會影響內容的行數)。 當調整 window 的大小時,contentRef (div with content) scrollHeight 與 clientHeight 進行比較,與上面的其他答案完全一樣。 如果 scrollHeight 更大,isClamped 將設置為 true,否則為 false。

現在,在包含內容的 div 中,如果 isExpanded 為 false(用戶未單擊“閱讀更多...”),則 className 將設置為“line-clamp-4”(這會將內容限制為 4 行),否則 className 將被設置為“line-clamp-none”(無鉗位)。

最后,在包含“Read More...”的 div 中,如果 isClamped 為真(因此文本被限制),將顯示。

import {useState, useRef, useEffect}

interface PostItemProps {
      post: Post
}

export default function PostItem({post}: PostItemProps){
    
  const contentRef = useRef<HTMLDivElement>(null)
  const [isClamped, setClamped] = useState(false)
  const [isExpanded, setExpanded] = useState(false)

  useEffect(() => {
    // Function that should be called on window resize
    function handleResize() {
      if (contentRef && contentRef.current) {
        setClamped(
          contentRef.current.scrollHeight > contentRef.current.clientHeight
        )
      }
    }

    // Add event listener to window resize
    window.addEventListener('resize', handleResize)

    // Remove event listener on cleanup
    return () => window.removeEventListener('resize', handleResize)
  }, []) // Empty array ensures that it would only run on mount

return (
    <div>
     <div ref={contentRef} className={`${ !exapnded ? 'line-clamp-4' : 'line-clamp-none' }> {post.content} </div>
     </div>
       {isClamped && (
          <div className="flex justify-end">
            <button
              className="font-bold text-title"
              onClick={() => setExpanded(true)}
            >
              See More...
            </button>
          </div>
        )}
    </div>
 )
}

一個基於 getClientRects().length 的簡單解決方案對我有用。

 $('.text-inline').each(function() { var textLineCount = $(this)[0].getClientRects().length; var lineClampValue = $(this).parent().css('-webkit-line-clamp'); if (textLineCount > lineClampValue) { $(this).parent().addClass('cut'); } });
 .text-block { overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; } .text-block.expand { -webkit-line-clamp: initial; } .show-text { display: none; } .cut+.show-text { display: initial; } .expand+.show-text { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script> <div class="text-block"> <span class="text-inline">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</span> </div> <button class="show-text" onclick="$(this).prev().addClass('expand')">Read more</button>

對於反應;

import React, { useRef } from 'react';

const textInput = useRef(null);

useEffect(() => {
const el = textInput.current;
setBtnShow(el.scrollHeight > el.clientHeight)
}, []);


<div ref={textInput} > Content </div>
  1. -webkit-line-clamp臨時設置為initial
  2. 計算行數,檢查它是否超過原始-webkit-line-clamp
  3. 如果是,則文本被夾住了。
  4. 重置-webkit-line-clamp

見小提琴: https : //jsfiddle.net/5cf0wp79/43/

暫無
暫無

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

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