html + css + jquery: Toggle Show More/Less Text

2020-03-06 04:10发布

I'm working on a personal project and I'm having a small issue:

This is my code code and currently works: http://jsfiddle.net/gvM3b/:

$(".show-more").click(function () {
    $(this).text("(Show Less)");
$(".text").toggleClass("show-more-height");
});​

The issue is that the "(Show More)" text changes to "(Show Less)" but not switches back when needed.

^That's one thing, an additional thing would be if you know how to add the [...] when it says show more but on the text. Been trying to figure it out but had to ask for a little of help, I'm new to jquery.

Thanks!

5条回答
放荡不羁爱自由
2楼-- · 2020-03-06 04:32

Like this:

$(".show-more").click(function () {        
    $(".text").toggleClass("show-more-height");
    if(!$(".text").hasClass("show-more-height")){
        $(this).text("Show Less");
    }else{
        $(this).text("Show More");
    }
});

updated fiddle

查看更多
戒情不戒烟
3楼-- · 2020-03-06 04:33

Update your jQuery:

$(".show-more").click(function () {
    if($(".text").hasClass("show-more-height")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }

    $(".text").toggleClass("show-more-height");
});

See http://jsfiddle.net/gvM3b/1/

查看更多
【Aperson】
4楼-- · 2020-03-06 04:42

I'd like to recommend the Jquery more less library which takes care of the 'Show More' 'Show Less' problem.

An alternative: cmtextconstrain

查看更多
▲ chillily
5楼-- · 2020-03-06 04:46

Use the ternary operator, for example:

$(".show-more").click(function () {
  var $this = $(this);
  $this.text($this.text() == "(Show Less)" ? "(Show More)" : "(Show Less)");
  $(".text").toggleClass("show-more-height");
});​

Or using .text() with a function:

$(".show-more").click(function () {
  $(this).text(function (i, oldText) {            
    return oldText == "(Show Less)" ? "(Show More)" : "(Show Less)";      
  });
  $(".text").toggleClass("show-more-height");
});​

DEMO.

查看更多
甜甜的少女心
6楼-- · 2020-03-06 04:55

Here's one more solution:

var i = 0;   

$(".show-more").on('click', function() {
    $(this).text( ++i % 2 ? "(Show Less)" : "(Show More)" );
    $('.text').toggleClass("show-more-height");
});

The fiddle: http://jsfiddle.net/gvM3b/6/

查看更多
登录 后发表回答