简体   繁体   中英

Toggle class and change size on an element using jQuery

I am trying to have a div change its properties on a click function. Some of the properties I am changing with a call to toggleClass() which is fine and works great. However I also want to resize the div based on the size of the viewport. In order to have access to those numbers I am changing the width and height with jQuery . This command looks like this:

$('.box').click( function() {
  $(this).toggleClass('box--grow', 0);
  $(this).css('width', w * .9);
  $(this).css('height', h * .9);
});

EDIT I want the height and width to go back to 100%.

I tried using the toggle class but that caused the entire div to disappear, and this solution doesn't work because when I click the div again the class is removed but the height is the same.

I am looking for a way to toggle this or to get the viewport width within the css . I tried both approaches but couldn't get anything to what I am looking for.

why not using CSS VH and VW values?

CSS:

.my90Class{
   width: 90vw;
   height: 90vh;
}

JS:

$('.box').click( function() {
   $(this).toggleClass("my90Class");
});

You need to get the window size first, and then put everything into combined .ready() and .resize() functions, to make it responsive.

function myfunction() {
    var w = $(window).width();
    var h = $(window).height();

    $('.box').click(function () {
        if ($(this).hasClass('box--grow')) {
            $(this).removeClass('box--grow');
            $(this).css({
                'width': '',
                'height': ''
            });
        } else {
            $(this).addClass('box--grow');
            $(this).css({
                'width': w * .9,
                'height': h * .9
            });
        }
    });
}

$(document).ready(myfunction);
$(window).on('resize', myfunction);

jsfiddle

You can check for the class with:

$(this).hasClass('box--grow')

Then to remove the class:

$(this).removeClass('box--grow');

And to add it back again:

$(this).addClass('box--grow');

The end would look like this save the original width and height before the event so you can add it back again:

var oldwidth = $('.box').css('width');
var oldheight = $('.box').css('height');

$('.box').click( function() {
  if($(this).hasClass('box--grow')) {
   $(this).removeClass('box--grow');
   $('.box').css('width', oldwidth);
   $('.box').css('height', oldheight);
  } else { 
   $(this).addClass('box--grow');
  }
});

untested but it would probably work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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