为何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
相关产品推荐
相关产品推荐

