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

扶醉桌前 提交于 2019-12-01 01:03:22

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/

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.

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

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/

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

An alternative: cmtextconstrain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!