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

如何在jQuery链式调用中用三元运算符控制animate方法参数?

实现jQuery animate方法的条件配置修改

你可以通过动态生成动画配置对象的方式,在不破坏链式调用结构的前提下满足需求,有两种简洁的实现方式:

方式一:直接使用三元表达式内联判断

这种方式适合逻辑简单的场景,直接在animate方法中传入条件判断后的配置:

$('#' + id)
    .delay(shortIntervalTime)
    .animate(id === 'block3' ? {opacity: 'show', bottom: '100px'} : {opacity: 'show'})
    .delay(longIntervalTime)
    .fadeOut(3000, function () {
      if (flag === true) {
        cycle1(nextId, false);
      } else {
        vdoList = insertIntoArray(vdoListTwo);
        console.log({ vdoList });
        addDisplay(firstAd, true, vdoList);
      }
    });

方式二:提前定义配置变量(可读性更好)

如果后续可能扩展更多条件,把配置逻辑抽离出来会让代码更易维护:

// 根据id生成对应的动画配置
const animateConfig = id === 'block3' 
  ? {opacity: 'show', bottom: '100px'} 
  : {opacity: 'show'};

$('#' + id)
    .delay(shortIntervalTime)
    .animate(animateConfig)
    .delay(longIntervalTime)
    .fadeOut(3000, function () {
      if (flag === true) {
        cycle1(nextId, false);
      } else {
        vdoList = insertIntoArray(vdoListTwo);
        console.log({ vdoList });
        addDisplay(firstAd, true, vdoList);
      }
    });

两种方式核心都是通过判断id的值,返回对应的动画配置对象,完全兼容原有的链式调用逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:36:26