2016-04-26 18 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>