Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
Cómo usar javascript para mostrar el botón cuando el artículo supera las dos líneas

¡Hay un problema que me ha estado molestando y recibí una solicitud! El botón más debe aparecer cuando el artículo tiene más de dos líneas. Si el artículo del usuario tiene exactamente dos líneas o no más de dos líneas, ¡no es necesario agregar el botón más!

He buscado muchos métodos, pero no he encontrado un método adecuado para lograr este requisito. ¡He hecho un diagrama explicativo y espero obtener su ayuda!

Gracias.

 $(function(){ let len = 70; $('.demo').each(function(){ if($(this).html().trim().length >len){ var str=$(this).html().substring(0,len-1)+"<button class='info-more'>...more</button>"; $(this).html(str); } }); });
 .content{ width: 200px; font-size: 15px; line-height: 1.5; 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> <div class="content">我是 james 我是文章 我是 james 我是文章 我是 james 我是文章 我 是 james 我是文章 我是 james 我是文章</div>

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede hacer esto con CSS Limite la longitud del texto a n líneas usando CSS

PERO pediste una versión JS

https://jsfiddle.net/mplungjan/zhnp3c17/

 $(function(){ let len = 10; let $but = $('<button class="info-more" >...more</button>') $('.content').each(function(){ const $textDiv = $(".text",this); // container let str = $textDiv.text().trim(); // string let diff = str.length - len; // difference in length console.log(diff) if (diff > 0) { $textDiv.text(str.slice(0,len)) // slice if needed $(this) .append($('<span class="moreSpan" hidden/>').text(str.slice(len))) .append($but.clone()); $(".info-more",this).toggle(diff>0); // show more if needed } }); $(".info-more").on("click",function() { const $moreSpan = $(this).closest("div").find(".moreSpan") $moreSpan.toggle() $(this).text($moreSpan.is(":visible")? "...less": "...more") }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <div class="content"><span class="text">我是 james 我是文章 我是 james 我是文章 我是 james 我是文章 我 是 james 我是文章 我是 james 我是文章</span> </div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!