简体   繁体   English

jQuery | 点击添加/删除课程| 最佳实践

[英]jQuery | Add/Remove Class on Click | Best Practise

today I had to set a number of images as a galery. 今天,我不得不为画廊设置许多图像。 On the mobile version of this site I had to stack the images because it wasn´t possible to show them in a row of 4 or something. 在该网站的移动版本上,我不得不堆叠图像,因为不可能连续显示4张图像。

Yet the images were quite high (350px) for a mobile view so I´ve decided to shrink them down to a height of 100px and make them clickable to extend to their full height. 但是,对于移动视图而言,图像非常高(350像素),因此我决定将其缩小到100像素的高度,并使其可单击以扩展到整个高度。

I did this just by adding or removing a class called "extended" which would set the height to 350px again. 我只是通过添加或删除一个名为“ extended”的类来做到这一点,该类将高度再次设置为350px。

The JavaScript I used for this works but yet I´m not sure if this is what you would call best practise or if it could be done easier: 我用于此的JavaScript可以运行,但是我不确定这是否是您所说的最佳实践,或者它是否可以更轻松地实现:

$('.galery__img--fragrance').on('click', function() {
    if($(this).hasClass('extended')) {
      $(this).removeClass('extended');
    } else {
      $(this).parent().find('.extended').removeClass('extended');
      $(this).addClass('extended');
    }
  });

I hope this question isn´t to redundant but I´m quite new to JS/jQuery and I want to do it right :-) 我希望这个问题不是多余的,但是我对JS / jQuery很陌生,我想做对了:-)

Edit: Maybe I should´ve mentioned that I wanted to make images collapse to a height of 100px if they were clicked again or if another image was clicked 编辑:也许我应该提到过,如果再次单击图像或单击其他图像,我想使图像折叠到100px的高度

Use .toggleClass() function to add/remove class simultanuously: 使用.toggleClass()函数可同时添加/删除类:

$('.galery__img--fragrance').on('click', function() {
    $(this).toggleClass('extended');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM