简体   繁体   中英

jquery - dynamically set a height or width when animated

I was curious on how to set a height or width dynamically based on when a div is animated.

JQUERY

$(document).ready(function() {
  var div1dimensions = 50 / 180 +'px';  
  $("#div1").animate({
    width: divdimensions,
    height: "100px",
    opacity: 1,
  }, 1500 );
});

Can I not just create a variable and place it where the width or height is? Or is that only for CSS values such as 100px?

Thank you.

Something that is important is that when using the object form of the .css() method, any numerical values placed there are inherently assumed to be pixel values:

$(document).ready(function() {
  var div1dimensions = (50 / 180);  

  $("#div1").animate({
    width: div1dimensions,
    height: 100,
    opacity: 1,
  }, 1500 );
});

Notice the lack of quotation marks. If you go about it this way, you can use a variable very easily:

$(document).ready(function() {
  var div1dimensions = (50 / 180),
      divHeight = div1dimensions * 1.5;  

  $("#div1").animate({
    width: divdimensions,
    height: divHeight,
    opacity: 1,
  }, 1500 );
});

Or any other variable calculation you wish, this is just an example. Additionally, as-of jQuery 1.4 you can pass in a function for that calculation. The example used in the jQuery .css() documentation modified to reflect your example:

$(document).ready(function() {
  var div1dimensions = (50 / 180);  

  $("#div1").animate({
    width: div1dimensions,
    height: function(i){
        return i * 50;
    },
    opacity: 1,
  }, 1500 );
});

That one can get tricky pretty quickly, and is really only helpful in very specific scenarios, but is handy when needed.

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