2016-08-04 71 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>