我有一个返回 true 或 false 的函数。现在我想在函数返回“true”时执行一些代码。
该函数确定元素在屏幕上是否可见。我取自here 。
该元素在页面加载后 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 运行时立即运行,但不会等到返回响应为 true。因此控制台日志总是错误的。 然后我实现了超时(仅用于测试目的)。 timeOut超时后,控制台日志始终为false。
它应该做什么: When/the 语句应该在结果变为 true 后运行。
最佳答案
您链接到的逻辑设计为在 scroll
事件处理程序中使用。它不返回 promise ,也不应该与 promise 一起使用。
要解决您的问题,请使用如下插件:
$.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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box foo"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="output"></div>
关于javascript - $.when($ ("").function() == true).then() 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45858132/