javascript jquery,点击放大图片,然后点击 agian 让它回到以前的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18969531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:53:47  来源:igfitidea点击:

jquery, click to enlarge image, then click agian make it go back to previous width

javascriptjquerycssfunctionclick

提问by Ham Dlink

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="https://i0.wp.com/www.thekitchenwhisperer.net/wp-content/uploads/2014/04/BelgianWaffles8.jpg" width="100" class="image" />

<script>
  $(document).ready(function() {
    $('.image').click(function() {
      $(this).css('width', '100%'); // original width is 500px 
    });
  });
</script>

How do add some codes so that i click it again, it goes back to the previous width(100px)?

如何添加一些代码,以便我再次单击它,它会回到以前的宽度(100px)?

回答by PSL

Like this?

像这样?

 $(document).ready(function(){
        $('.image').click(function(){
             $(this).css('width', function(_ , cur){
                  return cur === '100px' ? '100%' : '100px'
            });  
        });
    });

Fiddle

小提琴

回答by Flame

First of all I would replace the widthattribute for your img with CSS. Next up you can just remove the assigned inline-css (which is what jQuery adds) by calling

首先,我会用CSS替换img的width属性。接下来,您可以通过调用删除分配的 inline-css(这是 jQuery 添加的)

$(this).css('width', '');