简体   繁体   中英

returning css height to auto and width to a percentage not working in JQuery

I have setup a div with an original height at auto and a width at a percentage (48%).

I've allowed the div to be expanded on a user click. The div will expand to the height of 80% (from auto) and the width of 100% (from 48%). The expand is animated ( .animate )

So here's the code, for the expanding:

var e_p="in"; // The default of the div is in.

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

if (e_p == 'in'){
//the percentages i want the div to expand to...

var p_h= 0.8; 
var p_w= 1.0;

$(".box1").css("opacity","0");// i make the the other divs invisible

$('.box2').animate({

height:($(".wrapper").height()* p_h), // expand height

width:($(".wrapper").width()* p_w)},'fast'); //expand width

e_p = 'out'; //the div has just been expanded, so it will go back to normal size on the second user click.
}

Now the above works fine. It all expands like it's supposed to.

Here is the problem code to take it back to normal size (on the second user click);

else if (e_p == 'out'){ 
var p_w= 0.48;

    $(".box1").css("opacity","100");// make the the other divs visible

    $('.box2').animate({

    height:200, // make height 200px for the moment

    width:($(".wrapper").width()* p_w)},'fast'); //take the width back to its normal percentage
$(".box2").css("height","auto");//change the height back to auto....

    e_p = 'in'; //the div has just been squashed, so it will expand again on the third user click.
    }

Now the div goes back to 200px and the width looks like it goes back to 48% but when i zoom out of the page, the width should expand (to fill 48% percent of the page) but it doesn't.

And the height does not go back to auto as it does not expand with the content (text). The text just goes over the div and on the wrapper (as if an absolute position is set). Now there probably is allot of bad practice methods used here but guys, I'm completely new to jQuery so please bare with me.

Any suggestions?

Thanks

The problem is that you set the height to "auto" WHILE the animation is running.

You need to set the height to auto AFTER the animation completed (using a callback).

About the width, the problem is that when you set the width with the width() method, jQuery is setting the width to the absolute value that was computed at that time (instead of the explicit 48% value). To solve just make an explicit call to the css with 48% after the animation finished. Here is what you need for both problems:

$('.box2').animate({
    height:200, // make height 200px for the moment
    width:($(".wrapper").width()* p_w)},'fast', function() {
      $(".box2").css({height : "auto", width : '48%'});
});

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