$ .when($(“”)。function()== true).then()无法按预期工作

我有一个返回true或false的函数。 现在,我想在函数返回“true”后执行一些代码。

该函数确定元素在屏幕上是否可见。 我从这里拿走了它。

页面加载后1-2秒显示该元素。 但由于这也与用户的互联网连接有关,我不想使用setTimout函数。 我尝试了一些事情,发现它在if / else语句中有效,但在when / then时却没有。 任何想法,这里出了什么问题?

我测试了一些东西,见下面的代码

//below if else statement works fine and logs the correct result if($(".myClass").isOnScreen()==true){ console.log("true"); } else{console.log("false");} //however i would like to use this one and it doesn't seem to work $.when($(".myClass").isOnScreen()==true).then(function(){ console.log($(".myClass").isOnScreen()); setTimeout(function(){ console.log($(".myClass").isOnScreen()); },1000); }); 

when / then语句实际执行的操作:它在函数isOnScreen运行时立即运行,但不等到返回响应为真。 因此,控制台日志始终为false。 然后我实现了timeOut(仅用于测试目的)。 timeOut运行后,控制台日志始终为false。

它应该做什么:在结果变为true之后应该运行when /语句。

您链接的逻辑旨在用于scroll事件处理程序。 它不会返回一个承诺,也不应该与一个承诺一起使用。

要解决您的问题,请使用以下插件:

 $.fn.isOnScreen = function() { var element = this.get(0); var bounds = element.getBoundingClientRect(); return bounds.top < window.innerHeight && bounds.bottom > 0; } var $output = $('.output'), $foo = $('.foo'); // the important part: $(window).on('scroll', function() { $output.text('visible: ' + $foo.isOnScreen()); }); 
 .box { width: 50px; height: 50px; margin: 10px; background-color: #CCC; } .foo { background-color: #C00; } .output { position: fixed; top: 50px; right: 50px; }