简体   繁体   English

jQuery-动态设置动画时的高度或宽度

[英]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. 我很好奇如何根据div的动画时间动态设置高度或宽度。

JQUERY 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? 还是仅适用于CSS值(例如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: 重要的一点是,当使用.css()方法的对象形式时,放置在其中的任何数值固有地都假定为像素值:

$(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. 另外,从jQuery 1.4开始,您可以传递用于该计算的函数。 The example used in the jQuery .css() documentation modified to reflect your example: 修改了jQuery .css()文档中使用的示例以反映您的示例:

$(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. 那可以很快就变得棘手,实际上仅在非常特定的情况下有用,但是在需要时很方便。

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

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