jQuery animate使用变量设置width/height无动画效果的问题
jQuery animate变量设宽高动画失效问题解决
问题原因
- 直接用数字变量时,若元素初始宽高为
auto或未显式设置固定像素值,jQuery无法计算动画的起始与目标差值,导致动画失效。 - 拼接
+'px'转为字符串后,若起始宽高(如auto)与目标值单位逻辑不匹配,jQuery无法生成平滑过渡,直接跳转到目标尺寸。
解决方案
方法1:确保元素有明确初始像素宽高
先通过CSS给元素设置固定初始尺寸(避免auto):
.self-animate { width: 100px; height: 100px; }
再用数字变量传递参数,jQuery会自动补全px单位并生成平滑动画:
const selfw = 250; const selfh = 250; selfanimate.animate( { width: selfw, height: selfh, }, 500 );
方法2:动态获取当前元素宽高数值
如果元素初始宽高是动态的,先解析出当前宽高的数值,确保起始值为数字类型:
// 获取当前元素宽高的纯数值(去掉px单位) const currentWidth = parseInt(selfanimate.css('width'), 10); const currentHeight = parseInt(selfanimate.css('height'), 10); // 设置目标值 const selfw = 250; const selfh = 250; selfanimate.animate( { width: selfw, height: selfh, }, 500 );
方法3:统一使用带单位的字符串(需确保起始值为px格式)
若必须用字符串传递,先把元素当前宽高转为px格式,再执行动画:
// 先将当前宽高转为px格式,避免auto等非数值单位 selfanimate.css({ width: parseInt(selfanimate.css('width'), 10) + 'px', height: parseInt(selfanimate.css('height'), 10) + 'px' }); const selfw = '250px'; const selfh = '250px'; selfanimate.animate( { width: selfw, height: selfh, }, 500 );
内容的提问来源于stack exchange,提问作者DNa
相关产品推荐
相关产品推荐

