2015-09-25 77 views
0

我是Jquery的新手,可能需要一些幫助。在div動畫播放至400像素jquery div大一點再點擊div

https://jsfiddle.net/Ldvhx1ze/

後,我希望它去回落到200像素。我究竟做錯了什麼?

$(document).ready(function() { 
 

 
    if ($("#boks1").width() == 200) { 
 

 
     $("#boks1").click(function() { 
 
      $("#boks1").animate({ 
 
       width: "400px" 
 
      }); 
 
     }); 
 

 

 
    } else { 
 

 
     $("#boks1").click(function() { 
 
      $("#boks1").animate({ 
 
       width: "100px" 
 
      }); 
 
     }); 
 

 
    } 
 

 
});
html { 
 
    width: 100%; 
 
} 
 
#test { 
 
    background-color: blue; 
 
    height: 400px; 
 
    width: 400px; 
 
    margin: auto; 
 
    animation: new-post 1s ease infinite; 
 
} 
 
#wrapper { 
 
    height: 500px; 
 
} 
 
.container { 
 
    background-color: black!important; 
 
    margin-bottom: 40px!important; 
 
} 
 
#boks1 { 
 
    height: 400px; 
 
    width: 200px; 
 
    background-color: red; 
 
} 
 
#boks2 { 
 
    height: 400px; 
 
    width: auto; 
 
} 
 
#boks3 { 
 
    height: 400px; 
 
    width: auto; 
 
} 
 
#boks4 { 
 
    height: 400px; 
 
    width: auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div class="row"> 
 
     <div class="col-sm-3"> 
 
      <div id="boks1"></div> 
 
     </div> 
 
     <div class="col-sm-3"> 
 
      <div id="boks2"></div> 
 
     </div> 
 
     <div class="col-sm-3"> 
 
      <div id="boks3"></div> 
 
     </div> 
 
     <div class="col-sm-3"> 
 
      <div id="boks4"></div> 
 
     </div> 
 
    </div> 
 
</div>

+0

嘿,你的瀏覽器要求是什麼?你需要用JavaScript來做到這一點嗎? – jh3y

回答

1

你的if語句號召文檔準備,意爲boks1 click事件總是將是寬度動畫400像素之一。相反,檢測點擊,然後檢查寬度是多少。像這樣,

$(document).ready(function(){ 
    $("#boks1").click(function(){ 
     if ($("#boks1").width() == 200){ 
      $("#boks1").animate({width: "400px"}); 
     } else { 
      $("#boks1").animate({width: "200px"}); 
     } 
    }); 
}); 
+0

啊,真好!謝謝! –

1

您的if-else邏輯是錯誤的

這將解決這個問題。

$(document).ready(function(){ 

    $("#boks1").click(function(){ 
     if ($("#boks1").width() == 200){ 
      $("#boks1").animate({width: "400px"}); 
     } else { 
      $("#boks1").animate({width: "200px"}); 
     } 
    }); 

});