You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何jQuery animate宽高切换动画仅单向生效?

问题分析与解决

问题根源在于你的判断逻辑错误:jQuery的width()方法返回的是不带单位的像素数值,比如元素设为100%宽度时,它返回的是元素实际占据的像素值(比如1920),而你拿这个数值和字符串"100%"做比较,永远不会相等,所以按钮点击后只会一直执行放大到100%的逻辑,根本触发不了缩小到固定尺寸的动画。

给你两种修改方案:

方案一:用类标记状态(推荐)

用类来记录元素是否处于全屏状态,逻辑更清晰稳定:

$(".btn").click(function(){
  const $target = $(this).parent().parent();
  if($target.hasClass("full-screen")){
    $target.stop().animate({
      top: 0,
      left: 0,
      width: "500px",
      height: "300px"
    }).removeClass("full-screen");
  }else{
    $target.stop().animate({
      top: 0,
      left: 0,
      width: "100%",
      height: "100%"
    }).addClass("full-screen");
  }
})

方案二:通过父容器宽度判断

如果非要用宽度数值判断,可以拿元素当前宽度和父容器宽度对比(100%宽度等于父容器宽度):

$(".btn").click(function(){
  const $target = $(this).parent().parent();
  const parentWidth = $target.parent().width();
  if($target.width() === parentWidth){
    $target.stop().animate({
      top: 0,
      left: 0,
      width: "500px",
      height: "300px"
    });
  }else{
    $target.stop().animate({
      top: 0,
      left: 0,
      width: "100%",
      height: "100%"
    });
  }
})

另外注意:你原代码里animate的最后一个属性后面多了个逗号(height : "300px",),有些浏览器会因为这个语法错误导致代码失效,记得去掉。

内容的提问来源于stack exchange,提问作者Keith paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:50:47