2016-04-26 63 views
0

到目前为止,我已经有一个点击功能来扩展宽度,但不知道如何切换将其缩回到原始宽度。收缩后,.button应该再次显示“显示详细信息”。JQuery - 如何切换展开/收缩宽度?

小提琴链接:https://jsfiddle.net/fpw9apmc/

$('.button').click(function() { 
     $(".button").text("Hide Details"); 
     $(".expand").animate({ 
     width: "60%" 
     }, { 
      duration: 200, 
      specialEasing: { 
       width: 'linear' 
      } 
     }); 
    }); 

回答

1

这里是你的问题和编辑的代码Working Jsfiddle -

$('.button').click(function() { 
      var btnText = $(this).text(); 
      if(btnText === "Hide Details"){ 
      $(this).text("Show Details"); 
      $(".expand").animate({ 
      width: 0 
      }, { 
       duration: 200, 
       specialEasing: { 
        width: 'linear' 
       } 
      }); 
      }else{ 
       $(this).text("Hide Details"); 
      $(".expand").animate({ 
      width: "60%" 
      }, { 
       duration: 200, 
       specialEasing: { 
        width: 'linear' 
       } 
      }); 
      } 

     }); 
0

下面的脚本会帮助你。

var clicked = false; 
var previoswidth = 0; 
$('.button').click(function() { 
    $(".button").text("Hide Details"); 
    clicked = !clicked; 
    if (clicked) { 
     previoswidth = $(".expand").width(); 
     $(".expand").animate({ 
      width: "60%" 
     }, { 
      duration: 200, 
      specialEasing: { 
       width: 'linear' 
      } 
     }); 
    } 
    else { 
     $(".expand").animate({ 
      width: previoswidth 
     }, { 
      duration: 200, 
      specialEasing: { 
       width: 'linear' 
      } 
     }); 
    } 
}); 
0

FIDDLE HERE

单独申请肘节功能,以文本和宽度。这应该是关键

var width = $(".expand").width(); 
$('.button').click(function() { 
    $(this).text(function(i, text) { 
    return text === "Show Details" ? "Hide Details" : "Show Details"; 
    }) 
    var toggleWidth = $(".expand").width() == 0 ? "60%" : "0"; 
    $(".expand").animate({ 
    width: toggleWidth 
    }, { 
    duration: 200, 
    specialEasing: { 
     width: 'linear' 
    } 
    }); 
}); 
0

你可以做到这一点CSS过渡,并使用jQuery来切换类。

更新您的摆弄这个:https://jsfiddle.net/oykwmj9c/2/

的jQuery:

$('.button').click(function() { 
    if ($(".button").text() == "Show Details") { 
    $(".button").text("Hide Details"); 
    } else { 
    $(".button").text("Show Details"); 
    } 
    $(".expand").toggleClass("expanded"); 
}); 

CSS:

.expand { 
    background-color: red; 
    width: 0; 
    transition: width 1s ease-in-out; 
} 

.expanded { 
    width: 60% 
} 

.button { 
    color: #000; 
    font-size: 2em; 
} 

HTML:

<div class="expand"> 
    <a class="button" href="#">Show Details</a> 
</div>