簡體   English   中英

擴展具有固定高度的內容div

[英]Expanding content div with fixed height

我對組件有以下要求:

給定一個包含一些html / text的容器,如果內容達到指定的高度(例如:175px),則需要進行以下操作:

  • 截斷文本以適應175px高度
  • 在截斷點處需要附加“...更多”(這仍然需要在175px高度內)
  • 單擊“更多”時,內容需要擴展到其完整大小

它需要在所有瀏覽器(包括IE)中運行

我嘗試了很多庫:

readmore.js( http://jedfoster.com/Readmore.js/ ) - 這個讓我接近,但“更多”鏈接作為主要內容div之后的額外div而不是在斷點的末尾附加文本。

clamp.js( https://github.com/josephschmitt/Clamp.js/ ) - 這會在指定高度添加“...”,但不添加可點擊的更多鏈接,可以擴展並在IE中運行時出現問題

dotdotdot jQuery插件 - 和Clamp一樣的問題

做這樣的事情我有什么選擇? 有沒有辦法避免字體/像素數學?

我為您要完成的任務創建了一個可行的解決方案。 看看我的小提琴: https//jsfiddle.net/akm1essL/5/

JS

var container = document.getElementById('container');
var myText = container.getElementsByClassName('text-content')[0];
var spanEl = myText.childNodes[0];
var originalStr = myText.textContent.toString();
var truncatedStr;

// create the "More button" to be appended
var moreButton = document.createElement('span');
moreButton.setAttribute('class', 'readMore');
moreButton.setAttribute('id', 'moreButton');

checkHeight();

function checkHeight() {
    var maxHeight = 170;
    if (myText.clientHeight > maxHeight) {
        truncate();
    }
}

function truncate() {
    var str, hasButton;
    if (!hasButton) {
        myText.appendChild(moreButton);
        setButton("more");
        hasButton = true;
    }

    str = myText.textContent;
    truncatedStr = str.slice(0, str.lastIndexOf(' '));
    spanEl.textContent = truncatedStr;

    checkHeight(myText.clientHeight);
}

function showFull() {
    spanEl.textContent = originalStr;
    setButton();
}

function showTruncated() {
    spanEl.textContent = truncatedStr;
    setButton("more");
}

function setButton(display) {
    var btn = document.getElementById("moreButton");
    if (display === "more") {
        btn.textContent = "...More";
        btn.addEventListener("click", showFull);
        btn.removeEventListener("click", showTruncated);
    } else {
        btn.textContent = "...Less";
        btn.removeEventListener("click", showFull);
        btn.addEventListener("click", showTruncated);
        hasButton = false;
    }

}

為了縮短文本,此解決方案最初檢查內容高度,然后運行truncate()函數並從結尾一次縮短一個單詞的文本,直到它適合最大高度。 如果您需要縮短的文本最終為10,000字,這不是最好的方法,但我不確定您的用例。

HTML

<div id="container">
    <p class="text-content">
        <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nam suscipit, labore nemo distinctio incidunt laboriosam, est inventore totam voluptatem explicabo unde eius et. Provident harum, dolor tempora, aut consectetur excepturi. Dolorem aperiam distinctio ratione quam saepe eius ex, quasi, corporis molestias at laborum commodi, quis voluptatum possimus temporibus. Earum quis, et laudantium labore maxime fuga numquam explicabo!</span>
    </p>
</div>

我還在IE9,10,Chrome和FF中進行了測試,它適用於所有人。

暫無
暫無

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

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