如果width == 200px运行函数

时间:2013-02-28 19:46:44

标签: javascript jquery

这是jsFiddle showing the problem

我不确定为什么这不起作用:

if ($('#menu').width() == '200px') {
    alert("what");
}

我想在动画完成时显示警告。所以我假设我可以说,因为当动画完成时,元素的宽度为200px,它会显示警告。

4 个答案:

答案 0 :(得分:5)

1)您在动画完成之前检查了值。

2)你的宽度值是“200”而不是“200px”

这是jQuery文档。您需要在代码的回调部分执行检查。

$('#clickme').click(function() {
  $('#book').animate({
    opacity: 0.25,
    left: '+=50',
    height: 'toggle'
  }, 5000, function() {
    // Animation complete.   <---- your value check code goes here
  });
});

答案 1 :(得分:3)

jQuery.width会返回一个数字。您正在与字符串进行比较。

答案 2 :(得分:2)

检查更新的小提琴。我所做的是添加了一个'回调'函数,该函数在动画完成时执行。

$(this).stop().animate({ width: "200px" }, 250,
  function(){if ($('#menu').width() == '200') { alert("what"); } /* Callback Function */
 });

答案 3 :(得分:1)

.width()应该返回一个数字,而不是“### px”值,请尝试if ($('#menu').width() == 200) {