【问题标题】:jQuery: if ($('#indicador').width()jQuery: if ($('#indicador').width()
【发布时间】:2013-01-17 18:37:50
【问题描述】:

我能够制作一个宽度为 150 像素的条形动画。现在我试着让它回到原来的位置,但只有当它到达终点时。为什么条件: if ($('#indicator').width() > '149px') 不起作用?如何做好?

$(function(){        
  $("#play").click(function() {
    $("#indicator").animate({"width": "150px"}, 8400);
  });

  // indicador back to 0
  if ($('#indicator').width() > '149px') {
      $("#indicator").animate({"width": "1px"}, 100);
  }
});

在这里查看和玩:http://jsfiddle.net/SwkaR/

【问题讨论】:

  • 你的第二个函数在你的 DOM 准备好后立即运行,所以当你的动画完成时它不会触发!
  • console.log( $('#indicator').width() ); 应该告诉你原因。

标签: jquery conditional


【解决方案1】:

问题 1

在 DOM 准备好后立即触发将指标返回到其原始位置的函数 ($(function() { /* code for when the dom is ready */ });.

问题 2

由于 Javascript 是异步的,你应该为你的动画创建一个回调:

$(function(){

  $("#play").click(function() {
      $("#indicator").animate({"width": "150px"}, { duration: 8400, complete: function() {
          $("#indicator").animate({"width": "1px"}, 100);
      }});
  });

});

http://jsfiddle.net/zEwHx/

【讨论】:

    【解决方案2】:
    if ($('#indicator').width() > 149)
    

    jQuery width() 函数返回一个宽度值的整数,而不是带有单位的字符串,例如像素。

    您的程序存在逻辑错误。您可以链接animate() 函数。一旦第一个功能完成,它会自动移动到第二个。

    $(function(){
      $("#play").click(function() {
          $("#indicator").animate({"width": "150px"}, 8400).animate({ "width" : "1px" }, 100);
      });
    });
    

    【讨论】:

    • 我把你的答案放在这里,它似乎不起作用。我错过了什么? :jsfiddle.net/SwkaR/2
    • 但在小提琴中它的工作原理:D 我已经测试了 5 次 @drinchev
    • 是的,是的,你是对的 ;) 这就是我删除评论的原因!
    • 我仍然不太明白为什么这不起作用?:jsfiddle.net/SwkaR/2 您对条件的第一个回答是有道理的。
    • 好吧,它不起作用,因为您在 IF 语句中给出的条件仅被检查一次(在 DOM 加载时)并且它不会一次又一次地检查条件。我首先发布了.width(),因为我没有打开你的小提琴,也没有发现你的逻辑错误。
    【解决方案3】:

    Width 返回一个数字:

    .css(width) 和 .width() 的区别在于后者 返回一个没有单位的像素值(例如,400),而前者返回一个没有单位的值(例如,400px)

    【讨论】:

      【解决方案4】:

      您不能对像'149px' 这样的字符串进行算术比较。相反,您需要使用> 149。或者更好(更易读),>= 150

      【讨论】:

        【解决方案5】:

        试试这个...不要使用$(function) 使用.on...

        $("#play").on('click', function() {  
              $("#indicator").animate({"width": "150px"}, {duration:8400, complete:function(){
                  $("#indicator").animate({"width": "1px"}, 100);
              }});
        });
        

        jsFiddle Example

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-18
          • 1970-01-01
          • 2012-09-07
          • 2010-10-25
          • 1970-01-01
          相关资源
          最近更新 更多