Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
How to use javascript to set the Show More button to appear when the article exceeds two lines?

If you use javascript to set when the article paragraph exceeds two lines, the showMore button will appear.
If there are no more than two lines, showMore will not be displayed. At present, I use the word count method to set a problem, that is, it has more than two lines. It's OK, but the number of words has not reached 40, so the showMore button will not appear. I want to use the number of lines to judge, but how should I write it?

$(function(){
    let len = 40;
    $('.info_content').each(function(){ 
        if($(this).html().trim().length >len){   
            var str=$(this).html().substring(0,len-1)+"<button class='info-more'>...showMore</button>";
            $(this).html(str);
        } 
    });
});  
 .info_content{
    width: 250px;
    font-size: 15px;
    letter-spacing:1px;
    line-height: 1.5;
    margin-bottom: 8px;
    letter-spacing:0;
    overflow:hidden;
    text-overflow:clip;
    display:-webkit-box;
    -webkit-box-orient:vertical;  
    -webkit-line-clamp:2;
   }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="info_content">
     asd asdasdasd asd asda sdasd asdasd asd asdsda sdasdasda sdasd asda sdasd asd a
</h3>

 <h3 class="info_content">
asdasdasddsasfsdfsdfsdfsdf
</h3>


<!-- 第三組 -->
 <h3 class="info_content">
asdasdasdasgasdasdas   asdasda
asdasdasdasdasdasdasdasdasdd    asdasdasdasdasdasdasdasda
asdasdasdasdasdasdas     asdasdaasd     asda
</h3>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Create dummy element with a<br>a to simulate element with 2 lines.
Get its height and compare with other element.
If given element is bigger than dummy element add button after it (in will not work because it will be placed at the end of string which is hidden)

I have added inserAfter method from this answer to make adding button cleaner.

document.onreadystatechange = () => {
    if (document.readyState === 'complete') {
        const maxHeight = getElementMaxHeight('info_content');
        document.querySelectorAll('.info_content').forEach(infoContent => {
            infoContent.style.display = 'block';
            if (infoContent.clientHeight > maxHeight) {
                const button = document.createElement('button');
                button.classList.add('info-more');
                button.innerText = '...showMore';
                infoContent.insertAfter(button);
            }
            infoContent.style.display = '-webkit-box';
        });
    }
};

const getElementMaxHeight = (className) => {
    const element = document.createElement('div');
    element.classList.add(className);
    element.innerHTML = 'a<br>a';
    element.style.display = 'block';
    element.style.position = 'absolute';

    document.body.append(element);

    const height = element.clientHeight;

    element.remove();

    return height;
}

Element.prototype.insertAfter = function (newElement) {
    this.parentNode.insertBefore(newElement, this.nextSibling);
}
.info_content {
    width: 250px;
    font-size: 15px;
    line-height: 1.5;
    margin-bottom: 8px;
    letter-spacing: 0;
    overflow: hidden;
    text-overflow: clip;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}
<h3 class="info_content">
    asd asdasdasd asd asda sdasd asdasd asd asdsda sdasdasda sdasd asda sdasd asd a
</h3>

<h3 class="info_content">
    asdasdasddsasfsdfsdfsdfsdf
</h3>


<!-- 第三組 -->
<h3 class="info_content">
    asdasdasdasgasdasdas asdasda
    asdasdasdasdasdasdasdasdasdd asdasdasdasdasdasdasdasda
    asdasdasdasdasdasdas asdasdaasd asda
</h3>

<!-- 第四組 -->
<h3 class="info_content">
   qqq
</h3>

<!-- 第五組 -->
<h3 class="info_content">
  asdasdasdasgasdasdas asdasda s asdasda s asdasda 
</h3>

about 4 years ago · Juan Pablo Isaza Relatório

0

I came up with this solution but rather than having a button it's easier to make it happen with those elements.

here is the solution I came up with. (click the text to show more, click again to hide)

$(this).on("click",function(e){
  const c =e.target.className.includes("c2");
  if(c){
  $(e.target).removeClass("c2");  
  }else{
  $(e.target).addClass("c2");}
});
 .info_content{
    width: 250px;
    font-size: 15px;
    letter-spacing:1px;
    line-height: 1.5;
    margin-bottom: 8px;
    letter-spacing:0;
    overflow:hidden;
    text-overflow:clip;
    display:-webkit-box;
    -webkit-box-orient:vertical;  
    -webkit-line-clamp:2;
   }
.c2{
  -webkit-line-clamp: unset;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <h3 class="info_content">
     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut ornare metus. Integer gravida sollicitudin metus, eu aliquet mi varius at. Suspendisse elementum ex erat, at iaculis augue aliquet in. Ut nunc eros, egestas aliquet blandit a, viverra sed tellus.
    </h3>

     <h3 class="info_content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </h3>

     <h3 class="info_content">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque aliquam nunc ac viverra ullamcorper. Nam pellentesque aliquam enim, sit amet molestie enim iaculis non. Vestibulum sit amet diam. 
    </h3>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda