这个判断为什么不生效呢if($(".a").css("width") == 100){}

为什么这个判断不生效呢?我是想判断这个$(".a") 宽度是否为100px,是不是哪里写错了?

$(function(){
    $(".a").animate({width:"100px"},3000);    if($(".a").css("width") == 100){        console.log("100");
    }
})


蝴蝶刀刀
浏览 724回答 1
1回答

阿晨1998

首先 JavaScript 是异步加载,你那动画是3秒之后才加载的,所以宽度不会是100px,你只要加个定时器就可以了; 第二 你比较的时候少了单位 ‘px’, 修改后的代码如下<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <script src="jquery-1.9.1.min.js"></script>&nbsp; &nbsp; <title>Document</title></head><body>&nbsp; &nbsp; <div class="a">&nbsp; &nbsp; </div></body></html><script>$(function() {&nbsp; &nbsp; $(".a").animate({&nbsp; &nbsp; &nbsp; &nbsp; width: "100px"&nbsp; &nbsp; }, 3000);&nbsp; &nbsp; // console.log($(".a").css("width"))&nbsp; &nbsp; setInterval(function() {&nbsp; &nbsp; &nbsp; &nbsp; if ($(".a").css("width") == '100px') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("100");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, 3000)})</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript