【问题标题】:Animate element with specific class and CSS properties具有特定类和 CSS 属性的动画元素
【发布时间】:2021-09-12 09:10:59
【问题描述】:

我阅读了Jquery: How to check if the element has certain css class/style 并得到了这个工作 -

if ($(".box").css('display') == 'block')
{
  
    console.log("message  2 - Div with box class exists and css Block exists")


}

我阅读了how to create jquery slide left and right toggle 并得到了这个工作 -

 $(".box").animate({width: "toggle"});

不过,我似乎无法将上述两者结合在一起。这两次尝试都失败了 -

   // ($(".box").css('display') == 'block').animate({width: "toggle"});
   // ($(".box").css('display') == 'block').animate({width: "toggle"});


   var datebox = ($(".box").css('display') == 'block')
   datebox.animate({width: "toggle"})
   datebox.animate({width: "toggle"})

更新 1

我尝试了 Cucunber 的建议并得到了这个错误 - Uncaught TypeError: ".box".each 不是函数

更新 2

我通过将 $ 添加到 ('.box') 解决了更新 1 中突出显示的问题,Cucunber 根据我遇到的问题在下面更新了他的答案。

更新 3

我修改了 Cucunber 的解决方案,最终用这段代码解决了我的问题。

$(".box" ).each(function( index ) {


   if ($(this).css('display') == 'block' ) { 



console.log( index + ": " + $( this ) );
  



   }
})

【问题讨论】:

  • 请说明您的最终目标。这应该发生在单击按钮还是页面加载时? 1) 你有 2x 切换 - 如果你切换两次它会回到原来的位置,所以没有“似乎”发生任何事情 2) 你已经将 if (expression) 转换为 (expression) (没有 if) 3) 总是调试你的变量一个简单的console.log(datebox)会告诉你你有一个布尔值,所以true.animate..没有意义 - 总是检查控制台错误(你会得到这个代码)
  • if ($(".box").css('display') == 'block') $(".box").animate({width: "toggle"});
  • 与其使用.css("display") == "block",不如使用$(".box").is(":visible")作为“块”不会包括例如inlineinline-block(或任何其他“可见”显示属性)
  • 当日历小部件出现时,我想应用动画。我正在使用无限滚动数据选择器 (github.com/systemantics/infinite-scrolling-datepicker/blob/…),所以不幸的是 jqueryui (jqueryui.com/datepicker/#animation) 的说明无济于事。
  • 我在一个页面上有多个日期输入字段。我正在检查 css('display')=='block' 因为我只想将动画应用于可见日历。

标签: javascript html jquery css


【解决方案1】:

'$('.box').css('display') == 'block' 语句返回布尔语句。如果您知道,.animate 方法应该与 html 元素(选择器)一起使用。尝试使用这样的东西:

'$('.box').css('display') == 'block' && $('.box').animate({width: 'toggle'})

将其与'.each()' 结合,最终结果将是:

$('.box').each(function(){ $(this).css('display') == 'block' && $(this).animate({width: 'toggle'}) })

【讨论】:

  • 我正在尝试找到一种方法来选择具有特定类和 CSS 样式的元素。
  • 添加一些更改
  • 我收到此错误消息 - Uncaught TypeError: ".box".each is not a function
  • 我已经修改了我原来的问题
  • 加$到('.box')
猜你喜欢
  • 1970-01-01
  • 2017-02-10
  • 2023-03-23
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多