2016-08-04 86 views
0

我正在嘗試製作帶有一些圖片的網頁,您可以點擊它,然後展開。他們在第二次點擊後也必須縮小。我對JQuery很新,問題是當我點擊圖片時,它就會消失。切換圖片寬度

下面是代碼

$(document).ready(function(){  
    $(".imgclass").click(function(){  
    $(this).toggle(function() 
     {$(this).animate({width: "400px"});}, 
     function() 
     {$(this).animate({width: "120px"}); 
}); 
}); 
}); 

回答

3

檢查這個代碼,如果你期待一樣。只要你需要toggle

$(document).ready(function(){  
 
    $(".fotoklein").click(function(){  
 
    $(this).toggleClass('animate'); 
 
}); 
 
});
.fotoklein{ 
 
    width:100px; 
 
    height:100px; 
 
    background:#777; 
 
    color:#fff; 
 
    line-height:100px; 
 
    text-align:center; 
 
    -transition-duration:0.5s; 
 
    -webkit-transition-duration:0.5s; 
 
} 
 
.animate{ 
 
    width:400px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="fotoklein">Click me</div>

0

如果你想爲不同的圖像的變化ID =「fotoklein」類=「fotoklein」採用同樣的風格。

$(document).ready(function() { 
 
     var small={width: "120px",height: "120px"}; 
 
     var large={width: "400px",height: "400px"}; 
 
     var count=1; 
 
     $("#fotoklein").css(small).on('click',function() { 
 
      $(this).animate((count==1)?large:small); 
 
      count = 1-count; 
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="fotoklein" class="small" src="https://pbs.twimg.com/profile_images/657703841085935616/EulXOwHD.png">

希望這將幫助你..

+0

這個偉大的工程,謝謝你的快速反應 –

+0

這是我的榮幸。 –

0

你誤解了toggle()功能做什麼。 jQuery's toggle()只是顯示和隱藏元素。你需要像這樣的東西:

var big = false; 

$(".imgclass").click(function(){  

    if (big) { 
     $(this).animate({width: "120px"}); 
     big = false; 
    } else { 
     $(this).animate({width: "440px"}); 
     big = true; 
    } 

}); 

但是,使用Hitesh Misro的解決方案類更好。

0

var flag = false; 
 

 
$('.foo').click(function() { 
 
    if($(this).hasClass('focus')) { 
 
     $(this).animate({width: '-=2em'}, 300).removeClass('focus'); 
 
     flag = false; 
 
    } 
 
    else { 
 
     if(!flag) { 
 
      $(this).animate({width: '+=2em'}, 300).addClass('focus'); 
 
      flag = true; 
 
     } 
 
    } 
 
});
.foo{ 
 
color: #FFF; 
 
cursor: pointer; 
 
background: #456; 
 
height: 2em; 
 
margin: .5em; 
 
width: 4em;  
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div class="foo">Click</div> 
 
<div class="foo">Me</div>